leetcode 76. Minimum Window Substring

来源:互联网 发布:订餐的软件 编辑:程序博客网 时间:2024/06/05 20:41

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);    }};


0 0
原创粉丝点击