BM90 最小覆盖子串
给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 "" 。
注意:如果 s 中存在这样的子串,我们保证它是唯一的答案。
示例 1:
输入:s = "ADOBECODEBANC", t = "ABC"
输出:"BANC"
示例 2:
输入:s = "a", t = "a"
输出:"a"
提示:
1 <= s.length, t.length <= 105
s 和 t 由英文字母组成
进阶:你能设计一个在 o(n) 时间内解决此问题的算法吗?
解题思路:
滑动窗口
Python代码:
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param S string字符串
# @param T string字符串
# @return string字符串
#
from collections import Counter
class Solution:
def minWindow(self , S: str, T: str) -> str:
# write code here
occ = Counter(T)
counter = len(T)
i, j = 0, 0
res = ''
min_length = float('inf')
while j < len(S):
if occ[S[j]] > 0:
counter -= 1
occ[S[j]] -= 1
j += 1
while counter == 0:
if j - i < min_length:
min_length = j - i
res = S[i: j]
if occ[S[i]] == 0:
counter += 1
occ[S[i]] += 1
i += 1
return res