题目
给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 “” 。
注意:
对于 t 中重复字符,我们寻找的子字符串中该字符数量必须不少于 t 中该字符数量。
如果 s 中存在这样的子串,我们保证它是唯一的答案。
示例
示例 1:
输入:s = “ADOBECODEBANC”, t = “ABC”
输出:“BANC”
解释:最小覆盖子串 “BANC” 包含来自字符串 t 的 ‘A’、‘B’ 和 ‘C’。
示例 2:
输入:s = “a”, t = “a”
输出:“a”
解释:整个字符串 s 是最小覆盖子串。
示例 3:
输入: s = “a”, t = “aa”
输出: “”
解释: t 中两个字符 ‘a’ 均应包含在 s 的子串中,
因此没有符合条件的子字符串,返回空字符串。
提示:
- m == s.length
- n == t.length
- 1 <= m, n <= 105
- s 和 t 由英文字母组成
进阶:
你能设计一个在 o(m+n) 时间内解决此问题的算法吗?
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimum-window-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1. 字典排查
class Solution(object):
def minWindow(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
ls,lt = len(s),len(t)
if lt > ls:
return ""
if t == s[:lt]:
return t
nt,ns = 0,0
dic = defaultdict(int)
for i in t:
dic[i]+=1
dic1 = dic.copy()
# 获取初始窗口右边界
while nt<lt and ns<ls:
if s[ns] in dic1:
dic1[s[ns]] -= 1
if dic1[s[ns]] == 0:
del dic1[s[ns]]
ns+=1
nt+=1
else:
ns+=1
if nt < lt:
return ""
d = defaultdict(int)
# 获取初始窗口左边界
l,r = 0, ns
for i in s[l:r]:
d[i] += 1
while l < r:
if d[s[l]]>dic[s[l]]:
d[s[l]]-=1
l+=1
else:
break
res = [(len(s[l:r]),s[l:r])]
# 遍历
while l < ls:
#获取前面边界的值并删除
find = s[l]
# 如果前面边界的值存在于字典,那么找寻下一个出现相同值的地点
if find in dic:
d[find]-=1
l+=1
# 如果不存在下一个相同的值,跳出循环
if d[find] < dic[find] and find not in s[r:]:
break
# 开始在右边找寻,找到返回,同时如果找到的值在dic中有,则添加计数到d
while r < ls and s[r] != find:
if s[r] in dic:
d[s[r]]+=1
r+=1
# 找到的点添加计数
if s[r] == find:
d[find]+=1
r+=1
# 移动左边,得到最小子串
while l<r:
if (s[l] not in dic):
l+=1
else:
if d[s[l]] > dic[s[l]]:
d[s[l]]-=1
l+=1
else:
break
# 把每次获取到的最小子串添加到列表
res.append((len(s[l:r]),s[l:r]))
else:
l+=1
return sorted(res)[0][1]
818

被折叠的 条评论
为什么被折叠?



