Given a string S and a string T, find the minimum window in S which would 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 so covers all characters in T, return the emtpy string "" .
If There is multiple such windows, you is guaranteed that there would always being only one unique minimum window in S.
Method One: Dynamic programming, but time complexity and space complexity is too high
classSolution { Public: stringMinwindow (stringSstringT) {stringresult; if(s.length () = =0|| T.length () = =0)returnresult; if(S.length () < T.length ())returnresult; Vector<int> Layout ('Z'-'A'+1,0); for(inti =0; I < t.length (); i++) Layout[t[i]-'A']++; Vector<vector<vector<int>>> record (s.length () +1,vector<vector<int>> (s.length () +1, vector<int> ('Z'-'A'+1,0))); for(inti =1; I < s.length () +1; i++) {record[i][i][s[i-1]-'A']++; if(Equal (Layout.begin (), Layout.end (), Record[i][i].begin ())) {result= S.substr (I-1,1); returnresult; } } for(intL =2; L <= t.length (); l++){ for(inti =1; I < s.length () +2-L; i++) {Record[i][i+l-1] = record[i][i+l-2]; Record[i][i+l-1][s[i+l-2]-'A']++; if(Equal (Layout.begin (), Layout.end (), record[i][i+l-1].begin ())) {result= S.substr (I-1, L); returnresult; } } } returnresult; }};
Method Two: Double pointers, move the win_end pointer until it contains a string T, and then move the Win_start pointer down to the minimum window.
classSolution { Public: stringMinwindow (stringSstringT) {stringresult; if(s.length () = =0|| T.length () = =0)returnresult; if(S.length () < T.length ())returnresult; Vector<int> Expected_count ( the,0); Vector<int> Appeared_count ( the,0); for(inti =0; I < t.length (); i++) Expected_count[t[i]]++; intWin_start =0, Win_end =0; intMin_win_size = Int_max, Min_win_start =0; intappeared =0; for(Win_end =0; Win_end < S.length (); win_end++){ if(Expected_count[s[win_end]) >0) {Appeared_count[s[win_end]]++; if(Appeared_count[s[win_end]] <=Expected_count[s[win_end]]) appeared++; } if(appeared = =t.length ()) { while(Appeared_count[s[win_start] > Expected_count[s[win_start]] | | expected_count[s[win_start]] = =0) {Appeared_count[s[win_start]]--; Win_start++; } if(Min_win_size > (Win_end-win_start +1) ) {min_win_size= Win_end-win_start +1; Min_win_start=Win_start; } } } if(min_win_size = = Int_max)return ""; returns.substr (min_win_start,min_win_size); }};
Minimum window substring