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.
Solution:
class Solution {
public:
string minWindow(string s, string t) {
int ns = s.length(), nt = t.length();
if(ns < nt || !nt) return "";
vector<int> stat(128, 0), check(128, 0);
for(int i = 0; i < nt; ++i)
{
stat[t[i]]++;
check[t[i]] = 1;
}
int num = nt;
int i = -1, j = 0, minIdx = 0, minLen = ns + 1;
while(i < ns && j < ns)
{
if(num)
{
stat[s[++i]]--;
if(check[s[i]] && stat[s[i]] >= 0) num--;
}
else
{
if(i - j + 1 < minLen)
{
minLen = i - j + 1;
minIdx = j;
}
stat[s[j]]++;
if(check[s[j]] && stat[s[j]] > 0) num++;
j++;
}
}
if(minLen == ns + 1) return "";
else return s.substr(minIdx, minLen);
}
};