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> m1, m2;
int ns = S.size();
int nt = T.size();
if(ns == 0 || nt == 0 || ns < nt)
return "";
int start = 0, end = 0;
int minstart = 0;
int minsize = INT_MAX;
int count = nt;
for(int i=0; i<nt; i++)
++m1[T[i]];
while(true)
{
if(count == 0)
{
while(m2[S[start]] > m1[S[start]])
{
--m2[S[start]];
++start;
}
int size = end - start;
if(size < minsize)
{
minsize = size;
minstart = start;
}
}
if(end < ns)
{
++m2[S[end]];
if(m2[S[end]] <= m1[S[end]])
--count;
++end;
}
else
break;
}
if(minsize == INT_MAX)
return "";
return S.substr(minstart, minsize);
}
};