Minimum Window Substring
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.
Tips:
Maybe a int[256] is a better choice to replace map<char,int>
Solution:class Solution {
public:
string minWindow(string S, string T) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
sort(T.begin(),T.end());
map<char,int> count;
int total=T.size();
for(int i=0;i<T.size();++i){
++count[T[i]];
}
int start=0,end=0;
int len=S.size(),minstart=0;
for(int i=0;i<S.size();++i){
++end;
if(count.find(S[i])!=count.end()){
if(count[S[i]]-->0)
--total;
}
while(total==0&&start<end&&(count.find(S[start])==count.end()||
count[S[start]]<0)){
if(count.find(S[start])!=count.end())
++count[S[start]];
++start;
}
if(total==0&&end-start<len){
minstart=start;
len=end-start;
}
}
return total==0?S.substr(minstart,len):string("");
}
};