Closed labuladong closed 1 year ago
Q76. Minimum Window Substring https://leetcode.com/problems/minimum-window-substring/discuss/3874842/Java-sliding-window-solution
Problem: 76. 最小覆盖子串
[TOC]
滑动窗口:先找出所有的合规情况,然后从这些情况中找出答案,例如取最值。也就是说,窗口里的数据就是合规的数据,也就是说,直到找到合规的情况,左指针才右移。
滑动窗口问题要注意三点:
时间复杂度:O(n)
空间复杂度:O(n)
class Solution {
public String minWindow(String s, String t) {
Map<Character, Integer> need = new HashMap<>();
Map<Character, Integer> window = new HashMap<>();
for (char c : t.toCharArray()) {
need.put(c, need.getOrDefault(c, 0) + 1);
}
int left = 0;
int right = 0;
int valid = 0;
// 记录最小覆盖子串的起始索引及长度
int start = 0;
int len = Integer.MAX_VALUE;
while (right < s.length()) {
// c 是将移入窗口的字符
char c = s.charAt(right);
// 右移窗口
right++;
// 进行窗口内数据的一系列更新
if (need.containsKey(c)) {
window.put(c, window.getOrDefault(c, 0) + 1);
// 一定不要用 ==!要用 equals!
if (window.get(c).equals(need.get(c))) {
valid++;
}
}
// 判断左侧窗口是否要收缩
while (valid == need.size()) {
// 在这里更新最小覆盖子串
if (right - left + 1 < len) {
start = left;
len = right - left + 1;
}
// d 是将移出窗口的字符
char d = s.charAt(left);
// 左移窗口
left++;
// 进行窗口内数据的一系列更新
if (need.containsKey(d)) {
// 一定不要用 ==!要用 equals!
if (window.get(d).equals(need.get(d))) {
valid--;
}
window.put(d, window.get(d) - 1);
}
}
}
// 返回最小覆盖子串
return len == Integer.MAX_VALUE ? "" : s.substring(start, start + len - 1);
}
}
https://leetcode.cn/problems/minimum-window-substring/solutions/2372068/hua-dong-chuang-kou-jie-jue-zui-xiao-fu-0aub4/ https://leetcode.cn/problems/find-all-anagrams-in-a-string/solutions/2374641/hua-dong-chuang-kou-cha-zhao-zi-mu-yi-we-j13m/ https://leetcode.cn/problems/longest-substring-without-repeating-characters/solutions/2378565/hua-dong-chuang-kou-jian-cha-zhong-fu-zi-tm1j/
[567. Permutation in String] https://leetcode.com/problems/permutation-in-string/solutions/3879202/slide-window/
本期打卡已结算完成。报名最新一期的打卡活动 点这里