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的字符,持續(xù)forward滑動遍歷体斩,若前方出現(xiàn)重復字符示启,則窗尾更新(跟進)直到窗中沒有repeating字符(利用map找位置),過程中記錄滑動窗的最大長度作為結果。
具體:
在遍歷(j++)的過程中顽腾,實時將每個字符的最新位置保存到map中壁顶,char -> pos珠洗,
并且在過程中:
a. 若碰到map中出現(xiàn)過的字符x,為保持窗中沒有Repeating字符若专,從map取出之前最近出現(xiàn)過的字符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變?yōu)椋?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;
}
}