class Solution(object):
def minWindow(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
# 滑动窗口,不定长问题
from collections import Counter
temp = Counter(t)
# 定义一个与t一样的滑动窗口字典
window_dict = {}
for key in temp:
if key not in window_dict:
window_dict[key] = 0
# 判断是否满足条件
# 我们寻找的子字符串中该字符数量必须不少于 t 中该字符数量。
def isContains(temp, window_dict):
for key in temp:
if window_dict[key] < temp[key]:
return False
return True
star = 0
min_len = float('inf')
res = ""
for end in range(len(s)):
if s[end] in temp:
window_dict[s[end]] += 1
# 判断是否满足条件,如果满足star往右滑继续判断,寻找最小子串
while isContains(temp, window_dict):
if end-star+1 < min_len:
min_len = end-star+1
res = s[star:end+1]
if s[star] in window_dict:
window_dict[s[star]] -= 1
star += 1
return res
滑动窗口-4--LC76.最小覆盖子串
最新推荐文章于 2024-09-03 18:29:17 发布