class Solution:
def minWindow(self, s: str, t: str) -> str:
t_dict = {}
for char in t:
t_dict[char] = t_dict.get(char, 0) + 1 #dict.get(key, default_val_if_no_key)
#t_dict统计t串的字符数量,并在滑动观察子串sub时直接对其修改,表示sub对t的覆盖情况
r, l, min_r, min_l = 0, 0, len(s), 0
sub = ""
# min_r, min_l保存令sub长度最小的在s中的下标,初始值为超出范围的下标以标识是否存在这样的sub;r, l为当前窗口左右边界
while r < len(s):
# sub后加一字符
sub += s[r]
if s[r] in t_dict.keys():
t_dict[s[r]] -= 1
while self.cover(t_dict): #当sub能够覆盖t
if min_r - min_l > r - l:
min_r = r
min_l = l
#更新左边界,sub左减一字符
del_char = sub[0]
sub = sub[1:]
l += 1
if del_char in t_dict.keys():
t_dict[del_char] += 1
r += 1 #更新右边界
if min_r - min_l + 1 <= len(s):
#找到了最小子串
return s[min_l : (min_r + 1)] #list[star, end]是左闭右开的
else:
return ""
def cover(self, dic):
for v in dic.values():
if v > 0:
return False
return True
滑动窗口拓展:76最小覆盖子串
最新推荐文章于 2024-11-02 16:28:26 发布