[LeetCode]76. Minimum Window Substring
76. Minimum Window Substring
滑动窗口
import collections
class Solution(object):
def minWindow(self, s, t):
count, missing = collections.Counter(t), len(t)
left = 0 # 移动窗口
first, last = 0, 0 # 最终的窗口
for right, c in enumerate(s, 1):
# 统计剩下来的字符个数
missing -= count[c] > 0
count[c] -= 1
# 表示子串包含了T中所有的字符
if not missing:
# 设置left的值小于0是因为一开始计算的时候使用过一次,它的结果已经变成了0
# 移动左边的窗口,直到它对应的值不再小于0,也就是
while left < right and count[s[left]] < 0:
count[s[left]] += 1
left += 1
# 更新最小区间
if not right or right - left <= last - first:
first, last = left, right
return s[first:last]

关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法