-
什么是滑动窗口
在数组上维护一个 [ , ) 左闭右开可滑动的东西

-
滑动窗口的构建
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- 最⼩覆盖⼦串(困难)
- 字符串的排列(中等)
- 找到字符串中所有字⺟异位词(中等)
- ⽆重复字符的最⻓⼦串(中等)
本文深入探讨了滑动窗口的概念,展示了如何在数组上使用滑动窗口来解决字符串处理问题。通过一个具体的Java实现,解释了滑动窗口如何用于查找最小覆盖子串,并列举了滑动窗口在LeetCode中应用于解决如最小覆盖子串、字符串排列、字母异位词和无重复字符最长子串等难题。通过这个实例,读者可以更好地理解滑动窗口在字符串算法中的应用和重要性。
688

被折叠的 条评论
为什么被折叠?



