[LeetCode] 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.

这道题的关键是如何记录到当前位置各个有效字符出现的次数,要以O(1)的速度来获取某个字符的出现次数,必须以空间换取时间,我的想法有两个,一个是使用数组记录,另外一个就是使用HashMap来保存,当然,暂时使用的是数组,同时,再扫描数据的过程中统计有效次数有多少,依次有效的字符是出现再目标子字符中的,并且从当前开始字符到目前为止出现次数不大于目标字符串中该字符的出现次数。当有效次数达到了目标字符的总数之后,再从开始的字符开始扫描一遍以便获取开始的位置。再次过程中我们还要对现有的统计必要的更改。

class MinWindow
{
    
private:
    static const int CHARCOUNT = 256;
    int countN[CHARCOUNT],countT[CHARCOUNT];
    int usefulCount;
public:
    string minWindow(string S, string T) {
        usefulCount = 0;
        memset(countN,0, sizeof(countN));
        memset(countT,0, sizeof(countT));
        for(int i=0;i<T.length();i++)
        {
            countT[T[i]-'A']++;
        }
        int retBegin  = -1 ,retEnd = -1;
        int minLength = INT_MAX;
        int begin = 0,i=0;
        for(i=0;i<S.length();i++)
        {
            char c = S[i];
            if(countT[c-'A']==0)
                continue;
            if(countN[c-'A']<countT[c-'A'])
            {
                countN[c-'A']++;
                usefulCount++;
            }
            else
                countN[c-'A']++;
            if(usefulCount==T.length())
            {
                for(int k=begin;k<=
                    i;k++)
                {
                    char ic = S[k];
                    if(countT[ic-'A']==0)
                        continue;
                    if(countN[ic-'A']>countT[ic-'A'])
                        countN[ic-'A']--;
                    else if(countN[ic-'A']==countT[ic-'A'])
                    {
                        countN[ic-'A']--;
                        usefulCount--;
                        begin = k;
                        break;
                    }
                    
                }
                if(i-begin<minLength)
                {
                    retBegin = begin;
                    retEnd = i;
                    minLength = i-begin;
                }
                begin++;
                
            }
        }
        return retBegin == -1?"":S.substr(retBegin,retEnd-retBegin+1);
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值