论坛首页 编程语言技术论坛

[LeetCode] Minimum Window Substring

浏览 1477 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-05-02  

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.

 

两个指针,start,end。end往后面搜。存在满足要求的后,尽量压缩start。

 

class Solution {
public:
    string minWindow(string S, string T) {
        int c[256] = {0};
        bool cb[256] = {0};
        int cnt = T.size();
        for (char i: T) c[(int)i]++, cb[(int)i] = true;
        
        int start = 0, end = 0;
        int ls = S.size();
        int minlen = 10000;
        string minstr = "";
        while (end < ls && start < ls) {
            if (cb[S[end]]) {
                c[S[end]]--;
                if (c[S[end]] >= 0) cnt--;
                while (cnt == 0) {
                    if (cb[S[start]] == false) start++;
                    else if (c[S[start]] < 0) {
                        c[S[start]]++;
                        start++;
                    } else {
                        break;
                    }
                }
                if (cnt == 0) {
                    if (end - start + 1 < minlen) {
                        minlen = end - start + 1;
                        minstr = S.substr(start, minlen);
                    }
                    c[S[start]]++;
                    start++;
                    cnt++;
                }
            }
            end++;
        }
        return minstr;
    }
};

 

论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics