Counter奇技淫巧版本(1276ms):
class Solution:
def minWindow(self, s: str, t: str) -> str:
left, right = 0, 0 # [left, right)
need = Counter(t)
window = Counter()
ans = [0, len(s) + 1]
while right < len(s):
c = s[right] # 1. 增大窗口,寻找可行解
right += 1
if c in need:
window[c] += 1
while left < right and len(+(need - window)) == 0:
if right - left < ans[1] - ans[0]: # 只需要在这里更新答案!
ans = [left, right]
d = s[left] # 2. 缩小窗口,优化可行解
left += 1
if d in need:
window[d] -= 1
# 为什么不需要在这里更新呢?因为若满足条件,一定会进入内层循环,使用上面的代码更新
return s[ans[0]:ans[1]] if ans[1] != len(s) + 1 else ""
正常版本(120ms):
class Solution:
def minWindow(self, s: str, t: str) -> str:
left, right = 0, 0 # [left, right)
need = Counter(t)
window = Counter()
valid = 0
ans = [0, len(s) + 1]
while right < len(s):
c = s[right] # 1. 增大窗口,寻找可行解
right += 1
if c in need:
window[c] += 1
if window[c] == need[c]:
valid += 1
while left < right and valid == len(need):
if right - left < ans[1] - ans[0]: # 只需要在这里更新答案!
ans = [left, right]
d = s[left] # 2. 缩小窗口,优化可行解
left += 1
if d in need:
if window[d] == need[d]:
valid -= 1
window[d] -= 1
return s[ans[0]:ans[1]] if ans[1] != len(s) + 1 else ""