標籤:mini 一個 res nat ini ++ data 實現 which
題目描述
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 emtpy string"".
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
找出包含T所有字母的最小視窗。
注意:S=bba t=ba。此時right=2時,left=0,移動left時會++m[b],但是此時視窗內仍舊有一個b。所以在right移動時,m[b]=-1,即只要包含即--,而只有m[b]>=0時,才是有效,才會++count。同樣,在移動left時也是,只有m[b]>0時,才會count--。
這道題是字串處理的題目,和Substring with Concatenation of All Words思路非常類似,同樣是建立一個字典,然後維護一個視窗。區別是在這道題目中,因為可以跳過沒在字典裡面的字元(也就是這個串不需要包含且僅僅包含字典裡面的字元,有一些不在字典的仍然可以滿足要求),所以遇到沒在字典裡面的字元可以繼續移動視窗右端,而移動視窗左端的條件是當找到滿足條件的串之後,一直移動視窗左端直到有字典裡的字元不再在視窗裡。在實現中就是維護一個HashMap,一開始key包含字典中所有字元,value就是該字元的數量,然後遇到字典中字元時就將對應字元的數量減一。演算法的時間複雜度是O(n),其中n是字串的長度,因為每個字元再維護視窗的過程中不會被訪問多於兩次。空間複雜度則是O(字典的大小),也就是代碼中T的長度。代碼如下:
1 class Solution { 2 public: 3 string minWindow(string S, string T) { 4 if(S.length()==0) 5 return ""; 6 map<char, int> m; 7 for(int i=0;i<T.length();i++){ 8 if(m.find(T[i])!=m.end()) 9 m[T[i]]++;10 else11 m[T[i]]=1;12 }13 int left=0,right=0,min=S.length()+1,minStart=0,count=0;14 for(right=0;right<S.length();right++){15 if(m.find(S[right])==m.end())16 continue;17 m[S[right]]--;18 if(m[S[right]]>=0){19 count++;20 }21 while(count==T.length()){22 if((right-left+1)<min){23 min=right-left+1;24 minStart=left;25 }26 if(m.find(S[left])!=m.end()){27 m[S[left]]++;28 if(m[S[left]]>0)29 count--;30 }31 left++;32 }33 }34 string res="";35 if(min!=S.length()+1){36 res=S.substr(minStart,min);37 }38 return res;39 }40 };
LeetCode-Minimum Window Substring -- 視窗問題