最小覆盖子串-滑动窗口

链接: 最小覆盖字串.

from collections import defaultdict
class Solution:
    def minWindow(self, s: str, t: str) -> str:
        left,right = 0,0
        minlen = float('INF')
        match = 0
        start = 0
        need = defaultdict(int)
        window = defaultdict(int)
        for char in t:
            need[char] += 1
        while right < len(s):
            if s[right] in need:
                window[s[right]] += 1
                if window[s[right]] == need[s[right]]:
                    match += 1
            right += 1
            while match == len(need):
                if right - left < minlen:
                    minlen = right - left
                    start = left
            #更新最小字串

                if s[left] in need:
                    window[s[left]]-=1
                    if window[s[left]]<need[s[left]]:
                        match -=1
                left += 1
        return s[start:start+minlen] if minlen != float('INF') else ''
上一篇:collections 使用教程


下一篇:Python的collections原来这么好用!