Leetcode 76. 最小覆盖子串 minimum window substring - 滑动窗口+贪心策略

https://leetcode-cn.com/probl...python

解题思路

l 和 r 是当前目标串的最左下标和最右下标。 code

r 不断向前进。leetcode

l 在保证当前字母没有必要保留时向前进(没有必要指:这个字母不在目标字符串里 或者 这个字母当前数量已经超过要求),这是一个贪心策略字符串

cnt 统计了目标字母还须要多少。get

n 是 cnt 中的字母有几种的数量已经知足了。博客

ans 则是最终的答案string

代码

class Solution:
    def minWindow(self, s: str, t: str) -> str:
        import collections
        cnt = collections.Counter(t)
        ans = ''
        n = 0 # 当前我知足了 t 中的字母的种数
        l = 0
        for r, ch in enumerate(s):
            if ch not in cnt: 
                continue
            cnt[ch] -= 1
            if cnt[ch] == 0:
                n += 1
            while s[l] not in cnt or cnt[s[l]] < 0: # 看看当前 l 处的字母是否必要,不必 l 就加以
                if s[l] in cnt: cnt[s[l]] += 1
                l += 1
            if n == len(cnt):
                if not ans or len(ans) > r - l + 1:
                    ans = s[l: r+1]
        return ans

欢迎来个人博客: https://codeplot.top/
个人博客刷题分类:https://codeplot.top/categories/%E5%88%B7%E9%A2%98/io

相关文章
相关标签/搜索