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字符串中各个字符的个数。然后遍历s串,记录在满足包含T串中所有字符的前提下字符串左端的最右边的位置,然后求取当前情况下得到长度值,取所有这些长度的最小值并存储条件符合的字符串的起始点和终止点。总的时间复杂度为O(128n),即O(n),常数有点大。。。。

class Solution {
public:
    string minWindow(string s, string t) {
        vector<int> count[130];
        int cnt[130];
        for(int i = 0; i < 130; ++i) {
            cnt[i] = 0;
        }
        int ans = 0x3f3f3f3f;
        int sp, ep;
        int tlen = t.length();
        int slen = s.length();
        char ch = (t[0] >= 'a' && t[0] <= 'z' ? 'a' : 'A');
        int size;
        string ret = "";
        for(int i = 0; i < tlen; ++i) {
            cnt[(int)t[i]]++;
        }
        for(int i = 0; i < slen; ++i) {
            count[(int)s[i]].push_back(i);
            int t = 0x3f3f3f3f, tt;
            for(int j = 0; j < 128; ++j) {
                if(cnt[j] > 0) {
                    size = count[j].size();
                    if(size >= cnt[j]) {
                        tt = count[j][size-cnt[j]];
                    } else {
                        tt = -0x3f3f3f3f;
                    }
                    t = min(t, tt);
                    if(t < 0) break;
                }
            }
            if(ans > i-t+1) {
                ans = i-t+1;
                sp = t;
                ep = i;
            }
        }
        if(ans >= 0x3f3f3f3f) return ret;
        for(int i = sp; i <= ep; ++i) {
            ret += s[i];
        }
        return ret;
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值