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

LeetCode 76. Minimum Window Substring

时间:2018-09-07 14:10:36      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:sub   多少   etc   color   min   star   窗口   har   start   

典型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

标签:sub   多少   etc   color   min   star   窗口   har   start   

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

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