滑动窗口

leetcode 76.最小覆盖子串   https://leetcode-cn.com/problems/minimum-window-substring/submissions/

 

class Solution {
public:
    string minWindow(string s, string t) {
         string res;
        unordered_map<char, int> hs, ht;
        for(char c : t) ht[c]++;
        int cnt = 0;
        for(int i = 0, j = 0; i < s.size(); i ++)
        {
            hs[s[i]]++;
            if(hs[s[i]] <= ht[s[i]]) cnt++;
            while(hs[s[j]] > ht[s[j]]) hs[s[j++]]--;
            if(cnt == t.size())
            {
                if(res.empty() || i-j+1 < res.size())
                res = s.substr(j, i-j+1);
            }
        }
        return res;
    }
};

 

posted @ 2021-01-13 21:50  ATKevin  阅读(42)  评论(0编辑  收藏  举报