滑动窗口的思想
滑动窗口可以套用模板:
int left = 0;
int max;
for (int right = 0;right < s.length(); right++) {
// 当字符串不符合要求时,才向右滑动左指针left
}
leetcode 3. 无重复字符的最长子串
class Solution {
public int lengthOfLongestSubstring(String s) {
int left = 0;
int max = 0;
Map map = new HashMap();
for (int right = 0;right < s.length();right++) {
char ch = s.charAt(right);
if (map.containsKey(ch)) {
// 这里max()很重要,为了防止left指针后退
left = Math.max((int)map.get(ch) + 1, left);
}
map.put(ch, right);
max = Math.max(max, right - left + 1);
}
return max;
}
}
如果不是
left = Math.max((int)map.get(ch) + 1, left);
而是
left = (int)map.get(ch) + 1;
当指针到了第二个a时,因为 left = map.get('a) + 1, left会后退指向到第一个a的下一个下标,即1, 所以得到错误结果
right - left + 1 = 3 - 1 + 1 = 3。
159. 至多包含两个不同字符的最长子串
map只保存子串中的两个字符,若遇到新的字符,则删除最老的那个字符。
然后left再从最老的字符的下标 + 1开始。
比如 abba ,则 最老的字符为 第2个b。
class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
Map map = new HashMap<Character, Integer>();
int left = 0;
int max = 0;
for(int i = 0;i < s.length();i++) {
// map中只保存子串中的那两个字符,若遇到新的字符,则将最老的那个字符从map中移除。
if (!map.containsKey(s.charAt(i)) && map.size() == 2) {
int del_index = (int)Collections.min(map.values());
map.remove(s.charAt(del_index));
left = Math.max(del_index + 1, left);
}
map.put(s.charAt(i), i);
max = Math.max(max, i - left + 1);
}
return max;
}
}