title
给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 "" 。
注意:如果 s 中存在这样的子串,我们保证它是唯一的答案。
示例 1:
输入:s = "ADOBECODEBANC", t = "ABC"
输出:"BANC"
示例 2:
输入:s = "a", t = "a"
输出:"a"
提示:
1 <= s.length, t.length <= 105s和t由英文字母组成
solution
class Solution:
def minWindow(self, s: str, t: str) -> str:
need = collections.Counter()
for p in t:
need[p] += 1
count = collections.Counter()
def contains() -> bool:
# O(26)
for k, v in need.items():
if count[k] < v:
return False
return True
ans = ""
l = 0
for i, c in enumerate(s):
count[c] += 1
if need[c] == 0: continue
while contains() and l <= i:
while l <= i and need[s[l]] == 0:
l += 1
continue
tmp = s[l:i + 1]
# print(tmp, ans, len(tmp), len(ans), tmp<ans)
if not ans:
ans = tmp
elif len(tmp) < len(ans):
ans = tmp
elif len(tmp) == len(ans) and tmp < ans:
ans = tmp
# l向前移动
count[s[l]] -= 1
l += 1
else:
continue
return ans