Problem
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 =
T =
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 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.
Code
string minWindow(string S, string T) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int m = S.size(); int n = T.size(); int inText[256] = {0}; map<char,int> frequency; int min_len = INT_MAX; for(int i = 0;i < n; ++i){ ++inText[T[i]]; } bool found = false; int start = 0,matches = 0; string result; for(int i = 0;i < m; ++i){ char c = S[i]; if(inText[c] > 0){ ++frequency[c]; if(frequency[c] == inText[c]) matches += inText[c]; if(n == matches) found = true; if(found){ int j = start; for(;j <= i; ++j){ if(frequency.find(S[j]) != frequency.end()){ if(frequency[S[j]] == inText[S[j]]) break; --frequency[S[j]]; } } start = j; int len = i - j + 1; if(min_len > len){ min_len = len; result = S.substr(start,min_len); } } } } return result; }
No comments:
Post a Comment