思路:双指针+滑动窗口,使用哈希表记录每个字母最后一次出现的位置。
左闭右闭区间 [left,right]
,区间长度为 right - letf + 1
public int lengthOfLongestSubstring2(String s) {
Map<Character, Integer> map = new HashMap<>();
int left = 0, right = 0, res = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(right);
if (map.containsKey(ch)){
// left = 当前值最后一次出现的地方 + 1 ,使得[left,right]无重复值
left = Math.max(left, map.get(ch) + 1);
}
map.put(ch, right);
res = Math.max(res, right - left + 1);
right++;
}
return res;
}
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> map = new HashMap<>();
int i = -1, res = 0;
for (int j = 0; j < s.length(); j++) {
if (map.containsKey(s.charAt(j))){
i = Math.max(i, map.get(s.charAt(j)));
}
map.put(s.charAt(j), j);
res = Math.max(res, j - i);
}
return res;
}