[leetcode]Minimum Window Substring

Description

Problem Link
对于给定的字符串S,T,求S中包含T中所有字符的最短的子串。要求时间复杂度O(n)

e.g.
S = "ADOBECODEBANC"
T = "ABC"
return "BANC"

Possible Solution

分析:在这道题中,如果子串的结束位置固定了,那么最优解的开始位置也是固定的。而且随着end的增大,begin只会变大,不会变小。

基本思路:固定end,在满足有解得情况下,尽可能让begin变大。

如何判断有解?
代码中用一个bucket[128]来统计每个字符在T中出现的次数。
用一个counter[128]来实时统计,每个字符在当前的[begin,end]中出现的次数。
用一个remain变量来统计,还有多少字符的bucket>counter。当所有字符的bucket均<=counter,即可认为是有解的。

附代码:

class Solution {
private:
    static const int SIZE =  128+5;
public:
    string minWindow(string s, string t) {
        int n = t.size();
        int m = s.size();
        vector<int> bucket(SIZE,0);
        for (int i = 0; i < n; ++i)
            ++bucket[t[i]];
        int remain = n;
        int ansbegin = -1;
        int anslen = -1;
        vector<int> counter(SIZE,0);
        int begin = 0;
        for (int end = 0; end < m; ++end) {
            if (bucket[s[end]] > counter[s[end]]) {
                remain --;
            }
            counter[s[end]] ++;
            while (remain == 0) {
                int len = end - begin + 1;
                if (ansbegin == -1 || len < anslen) {
                    anslen = len;
                    ansbegin = begin;
                }
                if (bucket[s[begin]] <= counter[s[begin]] - 1) {
                    --counter[s[begin]];
                    begin++;
                }
                else break;
            }
        }
        if (ansbegin == -1) return "";
        else return s.substr(ansbegin,anslen);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值