76. 最小覆盖子串

原题链接:76. 最小覆盖子串

 

solution:

        滑动窗口:是Leetcode 438 的升级版

438. 找到字符串中所有字母异位词_anieoo的博客-CSDN博客

 

class Solution {
public:
    string minWindow(string s, string t) {
        unordered_map<char,int> hash;
        unordered_map<char,int> cnt;    //统计窗口中字母数量
        for(auto &c : t) hash[c]++; //存储t中所有字母和数量
        
        string res = "";

        int tot = hash.size();  //种类数目
        int kinds = 0;
        int n = s.size();
        for(int i = 0,j = 0;i < n;i++) {
            cnt[s[i]]++;    //窗口中字母++
            if(cnt[s[i]] == hash[s[i]]) kinds++;    //如果窗口中某个字母数量等于t中对应字母数量,则种类数+1
            while(cnt[s[j]] > hash[s[j]]) { //当窗口中最左端字母数量大于t中对应字母数量,滑动窗口
                cnt[s[j]]--;
                j++;
            }
            if(kinds == tot) {  //种类数相等则保存
                if(res == "" || res.length() > (i - j + 1))
                    res = s.substr(j,i - j + 1);
            }
        }

        return res;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值