leetcode76 最小覆盖子串

题目

给你一个字符串 S、一个字符串 T,请在字符串 S 里面找出:包含 T 所有字母的最小子串。
示例:
输入: S = "ADOBECODEBANC", T = "ABC"
输出: "BANC"
说明:
 如果 S 中不存这样的子串,则返回空字符串 ""。
 如果 S 中存在这样的子串,我们保证它是唯一的答案。
 

C++代码

class Solution {
public:
    string minWindow(string s, string t) {
        if(t == "")
            return "";
        unordered_map<char, int> mapt;
        int n = 0;
        for(int i=0; i<t.length(); i++)
        {
            if(mapt.find(t[i]) == mapt.end())
            {
                mapt[t[i]] = 1;
                n++;
            }
            else
               mapt[t[i]]++; 
        }

        int count = 0;
        int r = -1, l = -1;
        unordered_map<char, int> maps;
        int j=0;
        for(int i=0; i<s.length(); i++)
        {
            if(mapt.find(s[i]) != mapt.end())
            {
                if(maps.find(s[i]) == maps.end())
                    maps[s[i]] = 1;
                else
                    maps[s[i]]++;
                if(maps[s[i]] == mapt[s[i]])
                {
                    count++;
                    if(count == n)
                    {
                        while(1)
                        {
                            if(mapt.find(s[j]) != mapt.end())
                            {
                                maps[s[j]]--;
                                if(maps[s[j]] < mapt[s[j]])
                                {
                                    count--;
                                    j++;
                                    break;
                                }
                            }
                            j++;                            
                        }
                        if(l == -1 || ((i - j + 1) < (r - l)))
                        {
                            r = i;
                            l = j - 1;
                        }
                    }
                }
            }
        }
        if(l == -1)
            return "";
        return s.substr(l, r-l+1);
    }
};
 
 

猜你喜欢

转载自www.cnblogs.com/xumaomao/p/11350190.html