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:
string minWindow(string S, string T) {
map<char, int> charMap;
int ll = 0;
int len = 0;
for (int i = 0; i < T.length(); ++i) {
map<char, int>::iterator it = charMap.find(T[i]);
if (it == charMap.end())
charMap[T[i]] = 1;
else
++it->second;
}
int l = 0, r = 0;
int count = 0;
while(r != S.length()) {
map<char, int>::iterator it = charMap.find(S[r++]);
if (it == charMap.end()) {
continue;
}
--it->second;
if (it->second >= 0) {
++count;
}
if (count == T.length()) break;
}
if (count < T.length()) return "";
len = r;
int end = 0;
while (!end) {
end = 1;
while (l != S.length()) {
map<char, int>::iterator it = charMap.find(S[l]);
if (it == charMap.end()) {
++l;
continue;
}
if (it->second < 0) {
++it->second;
end = 0;
++l;
} else
break;
}
if (r-l < len) {
len = r-l;
ll = l;
}
while (r != S.length()) {
map<char, int>::iterator it = charMap.find(S[r++]);
if (it == charMap.end()) {
continue;
}
--it->second;
end = 0;
break;
}
if (r == S.length() && end == 1)
break;
}
string ret = S.substr(ll, len);
return ret;
}
};