leetcode76.最小覆盖子串c++超出时间限制

class Solution {
public:
    string minWindow(string s, string t) {
        int i=0,j=0;
        unordered_map<char,int> needMap;
        int needCnt=t.size();
        //needMap 代表:需要某个字符(key)若干个(value). needCnt表示当前缺失的字符数量。
        string res="";
        for (auto item : t){
            needMap[item]+=1;
        }
        while(j<s.size()){
            if(needMap.count(s[j])){
                if(needMap[s[j]]>0){
                    needCnt--;
                }
                needMap[s[j]]--;
            }
            while(needCnt==0){
                if((j-i+1)<res.size()||res.size()==0){
                    res=s.substr(i,j-i+1);
                }
                if(needMap.count(s[i])){
                    if(needMap[s[i]]==0){
                        needCnt++;
                    }
                    needMap[s[i]]++;
                }
                i+=1;
            }
            j+=1;
        }
        return res;
    }
};

最后一个测试用例超出时间限制,
使用字符数组替换哈希表:哈希表需要计算哈希值和内存分配,而字符数组只需要访问数组元素,因此速度更快。因此,可以将 unordered_map<char, int> needMap; 替换为 int need[128] = {0};,其中 128 是字符集大小。
另外 if (j - i < minLen) { // 不用 substr 函数
minLen = j - i;
start = i;
}

class Solution {
public:
    string minWindow(string s, string t) {
        int need[128] = {0};
        int needCnt = t.size();
        for (char c : t) {
            need[c]++;
        }
        int i = 0, j = 0, start = 0, len = INT_MAX;
        while (j < s.size()) {
            if (need[s[j]] > 0) { // 当前字符是 t 中的字符
                needCnt--;
            }
            need[s[j]]--;
            j++;
            while (needCnt == 0) { // 找到包含 t 所有字符的子串
                if (j - i < len) {
                    start = i;
                    len = j - i;
                }
                if (need[s[i]] == 0) { // i 指向的字符是 t 中的字符
                    needCnt++;
                }
                need[s[i]]++;
                i++;
            }
        }
        return len == INT_MAX ? "" : s.substr(start, len);
    }
};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值