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

相關文章
相關標籤/搜索