-
什么是滑动窗口
在数组上维护一个 [ , ) 左闭右开可滑动的东西
-
滑动窗口的构建
static String minWindow(String s,String t){
char[] ss = s.toCharArray();
HashMap<Character,Integer> need = new HashMap<>();
HashMap<Character,Integer> window = new HashMap<>();
int left = 0, right = 0;
int valid = 0;
// 记录最⼩覆盖⼦串的起始索引及⻓度
int start = 0, len = Integer.MAX_VALUE;
//need哈希表代表需要的字母和对应的个数
for (char c: t.toCharArray()){
need.put(c,need.getOrDefault(c,0)+1);
}
while (right < ss.length){
// c 是将移⼊窗⼝的字符
char c = ss[right];
// 右移窗口
right++;
//一系列更新操作
if (need.containsKey(c)){
window.put(c,window.getOrDefault(c,0)+1);
if (need.get(c) == window.get(c))
valid ++ ;
}
//判断何时左边进行收缩
while (valid == need.size()){
// 在这⾥更新最⼩覆盖⼦串
if (right - left < len){
start = left;
len = right - left;
}
char d = ss[left];
left ++;
//一系列更新操作
if (need.containsKey(d)){
if (window.get(d) == need.get(d))
valid--;
window.put(d,window.get(d)-1);
}
}
}
return len==Integer.MAX_VALUE? "":s.substring(start,start+len);
}
- 滑动窗口的应用
Leetcode- 最⼩覆盖⼦串(困难)
- 字符串的排列(中等)
- 找到字符串中所有字⺟异位词(中等)
- ⽆重复字符的最⻓⼦串(中等)