演算法分析課每週練習 Minimum Window Substring
阿新 • • 發佈:2019-01-09
題目
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.
貪婪演算法,遍歷s的時候,每讀進一個多餘的字母,嘗試收縮視窗。用dict(lexicon)來記錄字母出現次數
注: 又一個能在106中找到類似的題目def minWindow(self, s, t): need, missing = collections.Counter(t), len(t) i = I = J = 0 for j, c in enumerate(s, 1): missing -= need[c] > 0 need[c] -= 1 if not missing: while i < j and need[s[i]] < 0: need[s[i]] += 1 i += 1 if not J or j - i <= J - I: I, J = i, j return s[I:J]