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.
两个指针,start,end。end往后面搜。存在满足要求的后,尽量压缩start。
class Solution {
public:
string minWindow(string S, string T) {
int c[256] = {0};
bool cb[256] = {0};
int cnt = T.size();
for (char i: T) c[(int)i]++, cb[(int)i] = true;
int start = 0, end = 0;
int ls = S.size();
int minlen = 10000;
string minstr = "";
while (end < ls && start < ls) {
if (cb[S[end]]) {
c[S[end]]--;
if (c[S[end]] >= 0) cnt--;
while (cnt == 0) {
if (cb[S[start]] == false) start++;
else if (c[S[start]] < 0) {
c[S[start]]++;
start++;
} else {
break;
}
}
if (cnt == 0) {
if (end - start + 1 < minlen) {
minlen = end - start + 1;
minstr = S.substr(start, minlen);
}
c[S[start]]++;
start++;
cnt++;
}
}
end++;
}
return minstr;
}
};