15.5—细节实现题—Minimum Window Substring

来源:互联网 发布:知乎 收入 安排 编辑:程序博客网 时间:2024/06/10 12:37
描述
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.



#include<iostream>#include<string>#include<vector>#include<limits>using namespace std;string MinWindowSubstring(string S, string T){int len1 = S.size();int len2 = T.size();if (len1 < len2)return string("");bool flag = false;vector<int> ht1(256, 0);vector<int> ht2(256, 0);vector<int> ht(256, 0);for (int i = 0; i < len2; i++){ht1[T[i]]++;ht2[T[i]]++;}int beg = 0, end = 0;int pbeg = 0, pend = 0;int minwin = INT_MAX;for (; end < len1;end++){ht[S[end]]++;if (ht1[S[end]] != 0){ht1[S[end]]--;len2--;}if (len2 == 0){//ht1 = ht2;//方法一//len2 = T.size();//while (beg <= end)//{//if (ht1[S[beg]] == 0)//beg++;//else if (ht[S[beg]] >= ht1[S[beg]])//{//ht[S[beg]]--; beg++;//int tmp = beg - 1;//if (ht[S[tmp]] < ht1[S[tmp]])//{//beg--; break;//}//}////}//if (end - beg + 1 < minwin)//{//minwin = end - beg + 1;//flag = true;//pbeg = beg;//pend = end;//}//ht.assign(256, 0);//beg = end+1;//===ht1 = ht2;//方法二len2 = T.size();for (beg = end; beg >= 0; beg--){if (ht1[S[beg]] != 0){ht1[S[beg]]--; len2--;}if (len2 == 0){break;}}if (end - beg + 1 < minwin){minwin = end - beg + 1;flag = true;pbeg = beg;pend = end;}beg = end + 1;ht1 = ht2;len2 = T.size();}}if (flag)return S.substr(pbeg, minwin);elsereturn string("");}int main(){string S = "ADOBECODEBANC";string T = "ABC";string minwin = MinWindowSubstring(S, T);cout << "min window:" << minwin << endl;}