码迷,mamicode.com
首页 > Windows程序 > 详细

LeetCode[Hash Table]: Minimum Window Substring

时间:2015-02-04 21:50:22      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:leetcode   algorithm   c++   hash table   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   algorithm   c++   hash table   substring   

原文地址:http://blog.csdn.net/chfe007/article/details/43493467

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!