题目
题解
思路:滑动窗口,need记录t中每个字母的需要数量,needAll记录t的总字母数,两个指针同时从头起步,移动j,确定包含了t的所有字母,再移动i,计算最小的窗口;得到当前的最小窗口后再移动i,继续求下一个满足条件的窗口;
class Solution:
def minWindow(self, s: str, t: str) -> str:
need = collections.defaultdict(int)
for c in t:
need[c] += 1
needAll = len(t)
res = (0, float('inf'))
i = 0
for j, c in enumerate(s):
if need[c] > 0: #需要这个字母
needAll -= 1
need[c] -= 1 #不管需不需要都计数
if needAll == 0: #确定好j后求i
while True:
c = s[i]
if need[c] == 0: #当前i是最后一个能满足的字母
break
need[c] += 1 #不然就还能减小窗口
i += 1
if j - i < res[1] - res[0]: #取最小值
res = (i, j)
need[s[i]] += 1 #求下一个窗口,当前字母need+1
needAll += 1
i += 1
if res[1] > len(s):
return ""
else:
return s[res[0]:res[1]+1] #左闭右开