import collections
def minWindow(s: str, t: str) -> str:
need = collections.defaultdict(int)
for c in t:
need[c] += 1
needCnt = len(t)
i = 0
res = (0, float('inf'))
for j, c in enumerate(s):
if need[c] > 0:
needCnt -= 1
need[c] -= 1
if needCnt == 0: # 步骤一:滑动窗口包含了所有T元素
while True: # 步骤二:增加i,排除多余元素,直到 i 的位置 使窗口能包含t中的所有的元素,且此时窗口最小为止
c = s[i]
if need[c] == 0: #此时 i 的位置是满足条件的最小窗口,i再往右,窗口就不能包含所有的元素了,而i的左边是多余的元素
break
need[c] += 1
i += 1
if j - i < res[1] - res[0]: # 记录结果
res = (i, j)
need[s[i]] += 1 # 步骤三:i增加一个位置,寻找新的满足条件滑动窗口
needCnt += 1
i += 1
return '' if res[1] > len(s) else s[res[0]:res[1] + 1] # 如果res始终没被更新过,代表无满足条件的结果
s = input()
t = input()
print(minWindow(s,t))
手撕5_滑动窗口_最小覆盖子串
于 2024-04-11 00:58:21 首次发布
本文介绍了一个名为minWindow的函数,使用Python的collections库实现,目的是在给定字符串s中找到一个最小的连续子串,该子串包含给定目标字符串t的所有字符。算法通过维护一个滑动窗口来寻找满足条件的子串。
摘要由CSDN通过智能技术生成