leetcode3-无重复字符的最长子串
- 滑动窗口
需要记录左边界left。当右边界移动的时候,如果新加入的字符已经存在,那么需要更新左边界,让left取左边界和上一个字符位置的最大值。
之后更新字符的最新位置,同时更新max
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> map = new HashMap<>();
int left = -1, max = 0;
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(map.containsKey(c)){
left = Math.max(left, map.get(c));
}
map.put(c, i);
max = Math.max(max, i-left);
}
return max;
}
}

浙公网安备 33010602011771号