3. 无重复字符的最长子串
滑动窗口
滑动窗口
题目要求的是子串,所以一定是连续的,只要是连续的我们就要想到滑动窗口。这题要求拿到最长的不重复子串,我们只要维护滑动窗口中的内容是不重复的且满足长度最大。
关注点:
在冲突时保证左边界是最大的,比如abba
:b
冲突后a
也冲突,那么需要改变left为max(max, conflict(a).location)。
记得边界要+1,因为冲突点也是包含冲突字符的。
class Solution {
public int lengthOfLongestSubstring(String s) {
int max = 0;
int left = 0;
Map<Character, Integer> map = new HashMap<>();
for(int i = 0; i < s.length(); i ++) {
if(map.containsKey(s.charAt(i))) {
left = Math.max(map.get(s.charAt(i)) + 1, left);
}
max = Math.max(i - left + 1, max);
map.put(s.charAt(i), i);
}
return max;
}
}