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.
题目还是挺有意思的,需要注意的是如果T中包含两个A,那么最小窗口中也应该包括两个A,可以利用贪心算法,首先从0位置开始找到最短包含T字符串的子串,之后start向右移动一直到最小包含T的开始位置,之后重复这个过程.代码如下:
class Solution {
public:
string minWindow(string S, string T) {
int dest[256];
int src[256];
memset(dest,0,sizeof(dest));
memset(src,0,sizeof(src));
for(int i=0;i<T.size();++i){
dest[T[i]]++; 预处理目标字符串
}
int begin=-1;
int minlen=INT_MAX;
int found=0;
int start=0;
for(int i=0;i<S.size();++i){
++src[S[i]];
if(dest[S[i]]>0&&src[S[i]]<=dest[S[i]]) ++found; //如果当前字符在目标字符串中
//并且数量小于目标字符串则found加1;
if(found==T.size()) //找到包含所有T字符的最终位置
{
while(start<=i&&src[S[start]]>dest[S[start]])//去除掉开头的无效字符
{
--src[S[start]];
++start;
}
if(i-start+1<minlen) //记录最小位置
{
begin=start;
minlen=i-start+1;
}
src[S[start]]--; //跳过开头,从下一位置继续寻找
found--;
++start;
}
}
return begin==-1?"":S.substr(begin,minlen); //begin没有更新过返回空串
}
};