1、题目描述:
2、题解:
见力扣滑动窗口小结
模板:
int left = 0, right = 0;
while (right < s.size()) {`
// 增大窗口
window.add(s[right]);
right++;
while (window needs shrink) {
// 缩小窗口
window.remove(s[left]);
left++;
}
}
代码如下:
class Solution:
def minWindow(self, s: str, t: str) -> str:
#滑动窗口
need,window = collections.defaultdict(int),collections.defaultdict(int)
for c in t:
need[c] += 1
left,right = 0,0
valid = 0
res,min_= '',float('inf')
while right < len(s):
c = s[right]
right += 1
if c in need:
window[c] += 1
if window[c] == need[c]:
valid += 1
while valid ==len(need):
if right - left < min_:
res = s[left:right]
min_ = right - left
d = s[left]
left += 1
if d in need:
if window[d] == need[d]:
valid -= 1
window[d] -= 1
return res