题目:
给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 “” 。
注意:如果 s 中存在这样的子串,我们保证它是唯一的答案。
思路:
滑动窗口
解答:
class Solution:
def minWindow(self, s: str, t: str) -> str:
if t in s:
return t
if len(t)==1:
return ""
ls,lt=len(s),len(t)
# count代表需要元素的总个数,dic代表每个元素分别还需要的个数
count=lt
dic=defaultdict(int)
#dic.get(key,default=None):返回指定键的值,如果键不在字典中返回default设置的默认值
for c in t:
dic[c]+=1
#num记录当前满足条件的子串的长度
num=ls+1
#res记录结果字符串
res=""
i,j=0,0
while j<ls:
#print(dic,i,j,s[i:j+1])
if s[j] in dic:
dic[s[j]]-=1
if dic[s[j]]>=0:
count-=1
#窗口含i和j
while count==0:
if j-i+1<num:
num=j-i+1
res=s[i:j+1]
#print(count,dic,i,j,s[i:j+1])
#为达到 覆盖子串长度最小 的要求
#覆盖子串中的第一个字母一定是在t中的
#若不在,count不发生变化,需将i+=1
if s[i] in dic:
dic[s[i]]+=1
if dic[s[i]]>0:
count+=1
i+=1
#去除覆盖子串中的第一个字符,开始新一轮的统计
j+=1
return res