Topic
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.
Analysis
For more information: [Algorithm series 22] The Kid's window containing all the elements of T
Code
/ *--------------------------------------------* Date: 2015-02-24* sjf0115* title: 76.Minimum Window substring* Website: HT tps://oj.leetcode.com/problems/minimum-window-substring/* Result: ac* Source: leetcode* Summary:------------------------------------------------*/#include <iostream>#include <algorithm>#include <climits>using namespace STD;classSolution { Public:stringMinwindow (stringSstringT) {intSlen = S.size ();intTlen = T.size ();if(Slen <=0|| Tlen <=0){return ""; }//if intMinwinstart =0, Minwinend =0;intMinwinlen = Int_max;//Stores the total number of characters in t that have been encountered so far intCount =0;//Store the total number of different characters in T intneedfind[ the] = {0}; for(inti =0; i < tlen;++i) {++needfind[t[i]]; }//for //Stores the total number of different characters that have been encountered so far inthasfound[ the] = {0};intVal for(intStart =0, end =0; end < Slen;++end) {val = s[end];//Skip characters that are not in T if(Needfind[val] = =0){Continue; }//if++hasfound[val];if(Hasfound[val] <= Needfind[val]) {++count; }//if //Find a valid window if(count = = Tlen) {intStartval = S[start]; while(Needfind[startval] = =0|| Hasfound[startval] > Needfind[startval]) {if(Hasfound[startval] > Needfind[startval]) {--hasfound[startval]; }//if++start; Startval = S[start]; }//while //Update minimum window intCurwinlen = End-start +1;if(Curwinlen < Minwinlen) {Minwinlen = Curwinlen; Minwinstart = start; Minwinend = end; }//if}//if}//for if(count! = Tlen) {return ""; }//if returnS.SUBSTR (Minwinstart,minwinend-minwinstart +1); }};intMain () {solution solution;stringS"Acbbaca");stringT"ABA");cout<<solution.minwindow (s,t) <<endl;}
Run time
[Leetcode]76.minimum Window Substring