首页 > Windows开发 > 详细

LeetCode 76. Minimum Window Substring

时间:2018-09-07 12:58:37      阅读:110      评论:0      收藏:0      [点我收藏+]

典型Sliding Window的问题,维护一个区间,当区间满足要求则进行比较选择较小的字串,重新修改start位置。

思路虽然不难,但是如何判断当前区间是否包含所有t中的字符是一个难点(t中字符有重复)。可以通过一个hashtable,记录每个字符需要的数量,这个数量可以为负(当区间内字符数超过所需的数量)。还需要一个count判断多少字符满足要求了,如果等于t.size(),说明当前窗口的字串包含t里所有的字符了。

class Solution {
public:
    string minWindow(string s, string t) {
        unordered_map<char,int> hash; // char and the num it needs (it can be minus)
        int start=0;
        string res; int min_len=INT_MAX;
        for (char ch:t) hash[ch]++;    
        
        int count=0;
        for (int end=0;end<s.size();++end){
            if (hash.count(s[end])){
                --hash[s[end]];
                if (hash[s[end]]>=0) ++count;
                while (count==t.size()){
                    if (end-start+1<min_len){
                        min_len = end-start+1;
                        res = s.substr(start,end-start+1);
                    }
                    if (hash.count(s[start])){
                        ++hash[s[start]];
                        if (hash[s[start]]>0) --count;
                    }
                    ++start;
                }
            }
        }
        return res;
    }
};

 

LeetCode 76. Minimum Window Substring

原文:https://www.cnblogs.com/hankunyan/p/9603798.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!