leetcode76. Minimum Window Substring

leetcode76. Minimum Window Substring

题意:

给定字符串S和字符串T,找到S中的最小窗口,其中将包含复杂度O(n)中T中的所有字符。

例如,
S =“ADOBECODEBANC”
T =“ABC”
最小窗口为“BANC”。

注意:
如果S中没有覆盖T中所有字符的窗口,返回空字符串“”。

如果有多个这样的窗口,您可以确保在S中始终只有一个唯一的最小窗口。

思路:

一个right指针遍历s,每次遇到t中的字符,在map中减少一个,同时用一个count做统计,当t中所有字符被遍历的时候,做一次统计,并且将left指针移动,直到count != t.length() ,相当于一个窗口在s字符串上配合map表动态滑动。

ac代码:

C++

class Solution {
public:
    string minWindow(string s, string t) {
        int map[256] = {0};
        bool hash[256] = {false};
        int slen = s.length();
        int tlen = t.length();
        if(!slen || !tlen) return "";
        int left,right,res,cnt,minleft;
        minleft = cnt = left = right = 0;
        res = slen + 1;
        for(char ch:t)
        {  
            map[ch]++;
            hash[ch] = true;
        }
        
        while(right < slen)
        {
            if(hash[s[right++]] && --map[s[right - 1]] >= 0) 
                cnt++;
            
            while(cnt == tlen)
            {
                if(right - left < res)
                {
                    res = right - left;
                    minleft = left;
                }
                
                if(hash[s[left++]] && ++map[s[left - 1]] > 0 )
                {
                    cnt--;
                }
            }
        }
        if(res > slen) return "";
        return s.substr(minleft, res);
        
    }
};

python


posted on 2017-07-21 21:27  炮二平五  阅读(495)  评论(0编辑  收藏  举报

导航