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.
class Solution {
public:
int greater(int a[], int an, int b[], int bn){
int i;
if(an < bn){
return false;
}
for(i = 0; i < 256; i++){
if(a[i] < b[i]){
return false;
}
}
return true;
}
string minWindow(string S, string T) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int tflag[256];
int sflag[256];
memset(tflag, 0, 256 * sizeof(int));
memset(sflag, 0, 256 * sizeof(int));
int i, j;
int lens = S.size();
int lent = T.size();
for(i =0; i < lent; i++){
tflag[T[i]]++;
}
vector<int> wind(lens, 0);
int exist = false;
for(i = 0; i < lens && !exist; i++){
sflag[S[i]]++;
if(greater(sflag, i+1, tflag, lent)){
exist = true;
wind[i] = i + 1;
break;
}
}
if(!exist){
return "";
}
for(j = 0; j <= i; j++){
sflag[S[j]]--;
if(greater(sflag, i - j + 1, tflag, lent)){
} else {
wind[i] = i - j + 1;
sflag[S[j]]++;
break;
}
}
for(i++; i < lens; i++){
if(tflag[S[i]]){
if(S[i] == S[i - wind[i - 1]]){
for(j = i - wind[i - 1] + 1; j < i; j++){
if(tflag[S[j]]){
if(sflag[S[j]] > tflag[S[j]]){
sflag[S[j]]--;
} else {
break;
}
}
}
wind[i] = i - j + 1;
} else {
sflag[S[i]]++;
wind[i] = wind[i-1] + 1;
}
} else {
wind[i] = wind[i-1] + 1;
}
}
int minwind = 50000;
int pos=0;
for(i = 0; i < lens; i++){
if(wind[i] && wind[i] < minwind){
minwind= wind[i];
pos = i;
}
}
return S.substr(pos - wind[pos] + 1, wind[pos]);
}
};