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) {
int m = s.length();
int n = t.length();
string result = "";
if (m < n)
{
return result;
}
int num[256];
int count[256];
memset(num, 0, 256*sizeof(int));
memset(count, 0, 256*sizeof(int));
for (int i = 0; i < n; i++)
{
num[t[i]]++;
}
int left = 0;
int right = 0;
int foundChars = 0;
int minLen = m+1;
while (right < m)
{
int temp = (int)s[right];
if (num[temp] != 0)
{
count[temp]++;
if (count[temp] <= num[temp])
{
foundChars++;
}
}
if (foundChars == n)
{
while (num[s[left]] == 0 || count[s[left]] > num[s[left]])
{
if (count[s[left]] > num[s[left]])
{
count[s[left]]--;
}
left++;
}
if (right-left+1 < minLen)
{
minLen = right-left+1;
result = s.substr(left, minLen);
}
count[s[left]]--;
foundChars--;
left++;
}
right++;
}
return result;
}
};