Longest substring without repeating characters
要求找出字串中最長的不重複字元子字串
判斷重複的部分可以用 map 裝起來,重點是當右指針的位置的字元在前面重複過,
我們從 map 裡面拿出重複的位置,將佐指針定位為這個位置 + 1,這樣才知道下一次要從哪開始判斷
例如: aaaaab 如果不將左指針每次都往右移,長度會錯
另外拿出來的位置比左指針小也不用換了,因為當拿出來的位置比左指針小,
表示中間有重複過(有重複左指針才會動啊),所以也就不必判斷了
例子:an++--viaj
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int left = 0, right = 0;
int max = 0;
Map<Character, Integer> map = new HashMap<>();
for (right = 0; right < s.length(); right++) {
Character c = s.charAt(right);
if (map.containsKey(c)) {
int duplicatedIdx = map.get(c);
if (duplicatedIdx >= left)
left = duplicatedIdx + 1;
}
map.put(c, right);
max = Math.max(max, right-left+1);
}
return max;
}
point: 重複這件事如何判斷? 左指針移動表示什麼?