76. 最小覆盖子串
题目链接 | 76. 最小覆盖子串 |
---|---|
思路 | 滑动窗口 |
题解链接 | 两种方法:从 O(52m+n) 到 O(m+n),附题单(Python/Java/C++/C/Go/JS/Rust) |
关键点 | 如何跟踪子串与目标串的差距量(即less ) |
时间复杂度 | \(O(n+m)\) |
空间复杂度 | \(O(|\Sigma|)\) |
代码实现:
class Solution:
def minWindow(self, s: str, t: str) -> str:
cnt = defaultdict(int)
for ch in t:
cnt[ch] += 1
less = len(cnt)
answer_left, answer_right = -1, len(s)
left = 0
for right, ch in enumerate(s):
cnt[ch] -= 1
if cnt[ch] == 0:
less -= 1
while less == 0:
if right - left < answer_right - answer_left:
answer_left, answer_right = left, right
left_ch = s[left]
if cnt[left_ch] == 0:
less += 1
cnt[left_ch] += 1
left += 1
return "" if answer_left < 0 else s[answer_left:answer_right+1]