LeetCode[Hash Table]: 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.

对于这个题目,我毫无头绪,当我在Discuss上看懂这个解法的时候:https://oj.leetcode.com/discuss/10337/accepted-o-n-solution我觉得这个解法实在是太妙了!这个链接有关于这个解法的idea:https://oj.leetcode.com/discuss/5469/is-the-length-of-t-considered-constant-or-m

下面先贴出这个解法的代码:

    string minWindow(string S, string T) {
        int count = T.size();

        int  require[128] = { 0 };
        bool charSet[128] = { false };
        for (int n = 0; n < count; ++n) {
            require[T[n]]++;
            charSet[T[n]] = true;
        }

        int i = -1, j = 0;
        int minLen = INT_MAX, minIdx = 0;
        while (i < (int)S.size() && j < (int)S.size()) {
            if (count) {
                i++;
                require[S[i]]--;
                if (charSet[S[i]] && require[S[i]] >= 0) count--;
            }
            else {
                if (minLen > i - j + 1) {
                    minLen = i - j + 1;
                    minIdx = j;
                }
                require[S[j]]++;
                if (charSet[S[j]] && require[S[j]] > 0) count++;
                j++;
            }
        }

        return (minLen == INT_MAX ? "" : S.substr(minIdx, minLen));
    }

直观地理解这个算法是比较困难的,建议用一些例子跑起来,这样会比较容易理解这个算法为什么能到期望的目的。总之我很为这个解法而惊叹!

这个算法的时间性能表现如下图所示:

LeetCode[Hash Table]: Minimum Window Substring

LeetCode[Hash Table]: Minimum Window Substring

上一篇:windows下opengl扩展与多重纹理贴图


下一篇:64bitwin7 安装directshow不成功问题