76. 最小覆盖子串

题目链接 76. 最小覆盖子串
思路 滑动窗口
题解链接 两种方法:从 O(52m+n) 到 O(m+n),附题单(Python/Java/C++/C/Go/JS/Rust)
关键点 如何跟踪子串与目标串的差距量(即less
时间复杂度 O(n+m)
空间复杂度 O(|Σ|)

代码实现:

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]
posted @   WrRan  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
点击右上角即可分享
微信分享提示