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.
O(n)的解法思路参考:http://leetcode.com/2010/11/finding-minimum-window-in-s-which.html
代码:
class Solution {
public:
string minWindow(string S, string T) {
const int sLen = S.size();
const int tLen = T.size();
int needFind[256] = {0};
int hasFound[256] = {0};
for(int i=0; i<tLen; i++)
needFind[T[i]]++;
int minBegin = -1, minEnd, minLength = INT_MAX;
int count = 0;
for(int begin=0, end=0; end < sLen; end++)
{
if(needFind[S[end]] == 0) continue;
hasFound[S[end]]++;
if(hasFound[S[end]] <= needFind[S[end]])
count++;
if(count == tLen)
{
while(needFind[S[begin]]==0 ||
hasFound[S[begin]] > needFind[S[begin]])
{
if(hasFound[S[begin]] > needFind[S[begin]])
hasFound[S[begin]]--;
begin++;
}
int len = end-begin+1;
if(len < minLength)
{
minBegin = begin;
minEnd = end;
minLength = len;
}
}
}
if(minLength == INT_MAX) return "";
else return S.substr(minBegin, minLength);
}
};