Solution: Use two pointers: start and end.
First, move 'end'. After finding all the needed characters, move 'start'.
string minWindow(string S, string T) {
int N=S.length();
int M=T.length();
if(N<M) return "";
int need[256]={0};
int find[256]={0};
for(int i=0;i<M;i++)
need[T[i]]++;
int count=0,mStart=-1,mEnd=N;
int start=0,end=0;
for(;end<N;++end){
if(find[S[end]]<need[S[end]]){
count++;
}
find[S[end]]++;
if(count==M){
while(find[S[start]]>need[S[start]]||need[S[start]]==0){
find[S[start]]--;
start++;
}
if(end-start<mEnd-mStart){
mStart=start;
mEnd=end;
}
}
}
return mStart==-1?"":S.substr(mStart,mEnd-mStart+1);
}
No comments:
Post a Comment