leetcode 76. Minimum Window Substring

76. 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 empty string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.


题意:

求S串中包含T串的一个最小子串。

思路:

用两个指针st、ed来遍历S串,ed每次走到能包含T串的位置,st再走到刚好不能包含T串的位置,用这两个位置来更新答案。

怎么判断串是否被包含呢,使用num记录T串每个字母出现的次数,共有tot个不同字母,遍历T串的时候也记录字母出现的次数,如果次数和S串中的相等,计数变量cnt++,当cnt=tot的时候,这个子串就能包含T串了。

代码:

class Solution_76 {
public:
    string minWindow(string s, string t) {
        int n = s.length(), m = t.length();
        int nums[256] = {0};
        int numt[256] = {0};
        for (int i = 0; i < m; ++i) {
            numt[t[i]]++;
        }
        int tot = 0;
        for (int i = 0; i < 256; ++i) {
            if (numt[i]) tot++;
        }
        if (m == 0) return "";
        int cnt = 0, st = 0, ed = 0, best = n + 1, ansst = 0;
        while (ed < n) {
            while (ed < n) {
                nums[s[ed]]++;
                //printf("%d %d %c\n",nums[s[ed]],numt[s[ed]],s[ed]);
                if (nums[s[ed]] == numt[s[ed]]) {
                    cnt++;
                    if (cnt == tot) break;
                }
                ed++;
            }
            //find a qujian
            if (ed < n) {
                ed++;
//                printf("st:%d ed:%d cnt:%d\n",st,ed,cnt);
                for (; st < ed; st++) {
//                    printf("%d %d %c\n",nums[s[st]],numt[s[st]],s[st]);
                    if (nums[s[st]] == numt[s[st]]) {
                        if (best > ed - st) {
                            best = ed - st;
                            ansst = st;
                        }
                        nums[s[st]]--;
                        st++;
                        cnt--;
                        break;
                    }
                    nums[s[st]]--;
                }
//                printf("aft:st:%d ed:%d cnt:%d\n",st,ed,cnt);
            }
        }
        if (best == n + 1) return "";
        return s.substr(ansst, best);
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值