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

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

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


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值