lc 76. Minimum Window Substring
阿新 • • 發佈:2019-01-10
https://leetcode.com/problems/minimum-window-substring/
滑動視窗
1.如果要求只要出現就算,也就是所t='a'和t='aa'是一樣的話,那麼記錄一個出現過的字元的dict,只要這個set和目標set一樣大,就可以去記錄一下結果。這個結果可能是視窗右邊移動產生,也可能是視窗左邊移動產生的。
然後右界負責產生合法的,左界負責使之不合法。
2.如果是不光要出現,還要滿足數量要求的話,就都要用dict了。一旦一次右邊的移動導致d[c]==s[c]就是卡到了上界,那麼nums+=1,就是記錄幾個字元滿足了數量要求。
一旦一次左邊的移動導致d[c]==s[c]-1那麼nums-=1。每次我們用nums==len(s)來判斷是否是一個合法窗。
trick:
要兩層while巢狀,不要用並列的while:
while 不合法:
j+=1 並且更新狀態
while 合法:
記錄一下
i+=1 並且更新狀態
程式碼:
class Solution: def minWindow(self, s, t): """ :type s: str :type t: str :rtype: str """ ss={} d={} for c in t: d[c]=0 if c in ss: ss[c]+=1 else: ss[c]=1 t=ss nums=0 ans=[] i,j=0,-1 while nums<len(t) and j+1<len(s): # not satisfy j+=1 c=s[j]if c in t: d[c]+=1 if d[c]==t[c]: nums+=1 while nums>=len(t) and i<len(s): if len(ans) == 0 or ans[1] - ans[0] > j - i: ans = [i, j] c=s[i] if c in t: if d[c]==t[c]: nums-=1 d[c]-=1 i+=1 if len(ans)==0: return '' return s[ans[0]:ans[1]+1]