解:采用双滑动指针。
string minWindow(string s, string t) {
if(s.empty()||t.empty()){ return NULL;}
int t_array[256];
memset(t_array,0, sizeof(t_array));
int cmp_array[256];
memset(cmp_array,0,sizeof(cmp_array));
for (int i = 0; i < t.length(); ++i) {
t_array[t[i]]=t_array[t[i]]+1; //初始化一个数组map
}
int right=0,left=0;
int num_t=t.length();
int num_cmp=0;
int start=0,minlength=INT_MAX;
while(left<s.length()&&right<s.length()){
while(num_cmp<num_t&&right<s.length()){
if(t_array[s[right]]==0){
right++;
continue;
}
if(cmp_array[s[right]]<t_array[s[right]]){
num_cmp++;
}
cmp_array[s[right]]++;
right++;
if(num_cmp==num_t){
break;
}
} //第一个while中right指针移动
while(num_cmp==num_t&&left<right){
if(cmp_array[s[left]]==0){
left++;
continue;
}
if(cmp_array[s[left]]>t_array[s[left]]){
cmp_array[s[left]]--;
left++;
continue;
}
if(cmp_array[s[left]]==t_array[s[left]]){
if(minlength>right-1-left){
minlength=right-1-left;
start=left;
}
cmp_array[s[left]]--;
num_cmp--;
left++;
break;
} //第二个while中left指针移动
}
//cout<<start<<"--"<<minlength<<endl;
//cout<<left<<"---"<<right<<endl;
}
if(minlength!=INT_MAX){
string res;
for (int i = start; i <=start+minlength; ++i) {
res=res+s[i];
}
return res;
}else{ return "";}
}