1. 程式人生 > >【LeetCode】Minimum Window Substring

【LeetCode】Minimum Window Substring

Description

  Minimum Window Substring
  Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
  For example,
  S = ADOBECODEBANC
  T = ABC
  Minimum window is BANC.

Note:
  If there is no such window in S that covers all characters in T, return the empty string “”.
  If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

Code

  1. 我寫的冗長版
class Solution(object):
    def minWindow(self, s, t):
        def update(left, right, minL, s):
            while s[left] not in t:
                left += 1
            tmpL = right - left + 1
            if tmpL < minL:
                minL = tmpL
                return (True
, s[left:right + 1], left, right, minL) return (False, None, left, right, minL) rst = '' if len(s) < len(t) or len(t) == 0: return rst dict = {} for ch in t: if ch in dict: dict[ch] += 1 else: dict[ch] = 1
minL = 111111111111 left = 0 store = {} cnt = 0 # 視窗中已經涵蓋的字母數目 for right in range(len(s)): if s[right] in dict: if s[right] in store: store[s[right]] += 1 else: store[s[right]] = 1 if store[s[right]] <= dict[s[right]]: cnt += 1 # 把當前的詞涵蓋進去。如果這個詞出現的次數已經多於要求的次數了,那就不用cnt++了,但是也先把這個詞留著 if cnt == len(t): # 都找到了! (isShorter, rtn, left, right, minL) = update(left, right, minL, s) if isShorter: rst = rtn for i in range(left, right): if s[i] in store: store[s[i]] -= 1 left = i + 1 if store[s[i]] >= dict[s[i]]: (isShorter, rtn,left, right, minL) = update(left, right, minL, s) if isShorter: rst = rtn else: # 經過left的往右移動,現在window裡面沒能包含所有要求的字母,需要開始移動右邊界了 cnt -= 1 break return rst

2.大神寫的優雅版12 lines Python
    怎麼說,感覺人家寫得才是python……我好像寫了假程式碼……

Note