Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
方法:Sliding Window + Hashmap
思路:模擬變長滑動窗的方式,窗的起末位置定義為[i, j],滑動窗保持其中沒有repeating的字符,持續forward滑動遍歷,若前方出現重復字符,則窗尾更新(跟進)直到窗中沒有repeating字符(利用map找位置),過程中記錄滑動窗的最大長度作為結果。
具體:
在遍歷(j++)的過程中,實時將每個字符的最新位置保存到map中,char -> pos,
并且在過程中:
a. 若碰到map中出現過的字符x,為保持窗中沒有Repeating字符,從map取出之前最近出現過的字符x位置pos,窗的起始位置i跟上,更新到pos + 1;
b. 碰到map沒有字符,無特殊處理;
c. 每次計算當前窗的長度j - i + 1,若大 則更新max_length。
Time Complexity: O(N)
Space Complexity: O(N)
Example:
str = "abcdefc.."
例: j遍歷到c之前,"[abcdef]..",遇到c變為:"abc[defc].."
class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character, Integer> map = new HashMap<>();
int max_sublength = 0;
int left = 0;
for(int right = 0; right < s.length(); right++) {
if(map.containsKey(s.charAt(right)) && map.get(s.charAt(right)) >= left) {
left = map.get(s.charAt(right)) + 1;
}
map.put(s.charAt(right), right);
if(right - left + 1 > max_sublength) {
max_sublength = right - left + 1;
}
}
return max_sublength;
}
}