leetcode-双指针-76. 最小覆盖子串

 

解析参考:非常详细

https://blog.csdn.net/weixin_45629285/article/details/118674829

class Solution {
public:
    string minWindow(string s, string t) {

        unordered_map<char,int> s_map;
        unordered_map<char,int> t_map;
        for(int i = 0; i < t.size(); i++){
            t_map[t[i]]++;
        }
        int cnt = 0;
        string res;
        for(int i = 0, j = 0; i < s.size(); i++){
            s_map[s[i]]++;
            // 如果s_map[s[i]]<=t_map[s[i]],说明是t中必需元素,所以cnt++,
            // 如果不是t中元素,s_map[s[i]]肯定大于t_map[s[i]],因为t_map[s[i]]为0
            if(s_map[s[i]]<=t_map[s[i]])  
                cnt++;
            while(s_map[s[j]]>t_map[s[j]])
                s_map[s[j++]]--;  // 在使j++缩小窗口的同时,应该更新s_map
            // 如果是第一次或者本次窗口小于之前的窗口大小,更新res。
            if(cnt==t.size()){
                if(res.size()==0||(i-j+1)<res.size())
                    res = s.substr(j,i-j+1);
            }
            // 下次for循环从本次结束为止下一位开始,
            //cout<<"i: "<<i<<" "<<j<<" "<<cnt<<" "<<res<<endl;
        }
        return res;
    }
};

 

posted @ 2021-08-10 16:10  三一一一317  阅读(30)  评论(0)    收藏  举报