![17368230-862a03fdd0ce210f.png](https://i-blog.csdnimg.cn/blog_migrate/36b4db043c5fce1cd74373ad4c71b87a.png)
76. Minimum Window Substring
使用滑动窗口
主要思路是通过两次遍历找到所有可能的窗口(即从S中从start到end包含一个T),通过以下步骤实现:
为了减少时间复杂度,用mp记录T中所有字符出现的次数,使用cnt在S中寻找时计数,一旦找到一个T中的字符,cnt--,同时mp中当前字符的次数减1,当cnt等于0时,即找到了一个包含T的字符串,通过比较每个找到的字符串的长度,选择最短字符串。
class Solution(object):
def minWindow(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
mp = [0 for i in range(128)]
#计算t中每个元素出现的次数
for i in range(len(t)):
mp[ord(t[i])] += 1
#start end分别记录窗口的起止位置,res窗口大小,cnt表示t中还未包含的个数
start = end = head = 0
res = 2**31 - 1
cnt = len(t)
while end < len(s):
#mp[i]>0表示i在T中且滑动窗口未全部包含,更新cnt和map
if mp[ord(s[end])] > 0:
cnt -= 1
mp[ord(s[end])] -= 1
end += 1
#当前窗口T中的字符全部包含
while cnt == 0:
if end - start < res:
res = end - start
head = start
#如果mp[i]==0,start后移之后,就不全部包含了,应该更新cnt
if mp[ord(s[start])] == 0:
cnt += 1
mp[ord(s[start])] += 1
start += 1
return '' if res == 2**31-1 else s[head:head+res]
参考了牛客网上大佬们的答案