#滑动窗口学习总结
##通用模板
通用模板如下:
*//windows 是符合要求的滑动的窗口;有时候形式可以改变一下*
HashMap<Character,Integer> windows = new HashMap<>();
*//need 有的类型问题需要对比时候存放集合*
HashMap<Character,Integer> need = new HashMap<>();
*//如对比类型时获取,对比值集合*
char[] ps = s.toCharArray();
for(char x : ps) {
need.put(x, need.getOrDefault(x, 0)+1);
}
int left = 0,right = 0;
int res = 0; //或者其他要求的输出
while (right < s.length()) {
char c = s.charAt(right);
right++;
**//如需要则补充具体业务**
...
while ( 内循环条件) {
char d = s.charAt(left);
**//如需要则补充具体业务**
...
**//如符合时候的输入**
...
left++;
}
//如符合时候的输出
...
}
##案例学习
###lecode3
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
public static int lengthOfLongestSubstring(String s) {
if(s == null || s.length() == 0){
return 0;
}
HashMap<Character,Integer> windows = new HashMap<>();
int left = 0,right = 0;
int max = 0;
while (right < s.length()) {
char c = s.charAt(right);
right++;
windows.put(c, windows.getOrDefault(c, 0)+1);
while (left <= right && windows.get(c) > 1) {
char d = s.charAt(left);
windows.put(d, windows.getOrDefault(d, 0)-1);
left++;
}
Math.max(max, right-left);
}
return max;
}