从头做leetcode之leetcode 76 最小覆盖子串

76.最小覆盖子串

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

示例:

输入: S = “ADOBECODEBANC”, T = “ABC”
输出: “BANC”
说明:

如果 S 中不存这样的子串,则返回空字符串 “”。
如果 S 中存在这样的子串,我们保证它是唯一的答案。

class Solution {
public:
    string minWindow(string s, string t) {
        if(t.size() > s.size()) return "";
        unordered_map<char,int> m;
        unordered_map<char,int> tmp;
        for(int i = 0;i < t.size();i++){
            m[t[i]]++;
        }
        int count = 0,reslength = INT_MAX;//记录已匹配完字符的个数
        int left = 0,right = 0;
        string res = "";
        while(right < s.size()){
            if(m.count(s[right])){
                tmp[s[right]]++;
                if(tmp[s[right]] == m[s[right]]){
                    count++;
                }
            }
            right++;
            while(count == m.size()){
                if(right - left < reslength){
                    reslength = right - left;
                    res = s.substr(left,reslength);
                }
                if(m.count(s[left])){
                    tmp[s[left]]--;
                    if(tmp[s[left]] < m[s[left]]){//有可能出现有多个匹配字符的情况,所以while
                        count--;
                    }
                }
                left++;
            }
        }
        return res;
    }
};

通过时间:
从头做leetcode之leetcode 76 最小覆盖子串_第1张图片

你可能感兴趣的:(从头做leetcode之leetcode 76 最小覆盖子串)