minimum-window-substring

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没有更新过返回空串          
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值