LeetCode76:滑动窗口 Minimum Window Substring(python)

题解:滑动窗口

import collections
class Solution(object):
     def minWindow(self,s:str,t:str)->str:

############分析过程#######################
         #Sliding Window + 2 pointers
         # S= 'A (D O B E (C (O D E B A) N C)';T='ABC'
         # left                      @
         # right                           @
         # dic:{'A':1,'B':0,'C':1}
         # count:{'A':1,'B':1,'C':1}
         # matchNum:2
         # rstNum:right-left+1=5-0+1=6,10(不更新),6(不更新),7(不更新),4
         # rst:A D O B E C
         #    (D O B E C O D E B A)
         #    (C O D E B A)
         #    (O D E B A N C)
         #    (B A N C)

###################code###################

         if not s or not t: return ''
         left = right = matchNum = rstMin = 0
         rstMin = 2 ** 31
         dic = {}
         rst = ''
         count = collections.Counter(t)#={'A':1,'B':1,'C':1}
         while left <= right and right < len(s):
             char = s[right]
             dic[char] = 1 if char not in dic else dic[char] + 1
             if dic[char] <= count[char]: matchNum += 1
             while matchNum == len(t):
                 if rstMin > right - left + 1:
                     rstMin = right - left + 1
                     rst = s[left:right + 1]
                 dic[s[left]] -= 1
                 if dic[s[left]] < count[s[left]]: matchNum -= 1
                 left += 1
             right += 1
         return rst

你可能感兴趣的:(python)