我们的口号是:使用最简洁的代码,完成AC:)
题目介绍
给你一个字符串 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代码
class Solution:
def minWindow(self, s: str, t: str) -> str:
needs, missing = collections.Counter(t), len(t)
i = I = J = 0
for j, c in enumerate(s, 1):
missing -= needs[c] > 0
needs[c] -= 1
if not missing:
while i < j and needs[s[i]] < 0:
needs[s[i]] += 1
i += 1
if not J or j - i <= J - I:
I, J = i, j
return s[I: J]