leetcode 最小覆盖字串

给你一个字符串 S、一个字符串 T,请在字符串 S 里面找出:包含 T 所有字母的最小子串。

示例:

输入: S = "ADOBECODEBANC", T = "ABC"
输出: "BANC"

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-window-substring

思路:以i为结尾向前找,直到满足条件,但是这样复杂度过高,我们分析可以得到单调性,j指针是不会后退的,每次更新i指针直到有答案,每次也要更新i指针,当出现冗余元素时j指针后移

class Solution {
public:
    string minWindow(string s, string t) {
        unordered_map<char,int> h1;
        unordered_map<char,int> h2;
        int cot=0;
        for(auto c:t){
            if(!h1[c])cot++;
            h1[c]++;
        }
        string res="";
        for(int i=0,j=0,c=0;i<s.size();++i){
            h2[s[i]]++;
            if(h2[s[i]]==h1[s[i]])c++;
            while(h2[s[j]]>h1[s[j]])h2[s[j++]]--;
            if(c==cot){
                if(res.empty()||res.size()>i-j+1){
                    res=s.substr(j,i-j+1);
                }
            }
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/clear-love/p/11378993.html