力扣 30.串联所有单词的子串

文章讨论了一个关于编程挑战的问题,如何在给定字符串中找到所有包含给定单词子串的起始位置。原始解决方案存在超时问题,改进后的`findSubstring`方法通过避免重复迭代解决了这个问题,提高了时间效率。
摘要由CSDN通过智能技术生成

力扣 30.串联所有单词的子串

在这里插入图片描述
在这里插入图片描述
代码:(超时

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> res;
        int w_size=words.size();
        int item_size=words[0].size();
        int len=w_size*item_size;
        map<string,int> words_map;
        for(int i=0;i<w_size;i++)//初始化
            words_map[words[i]]++;

        for(int i=0;i<s.size()-len+1;i++){//遍历
            if(find(s,words_map,i,len,item_size))//串联子串
                res.push_back(i);
        }
        return res;
    }

    bool find(string s,map<string,int>words_map,int i,int len,int item_size){
        int index=i;
        for(i;i<index+len;i=i+item_size){
            string key=s.substr(i,item_size);
            if(words_map[key] > 0){//word匹配单词
                words_map[key]--;
            }
            else //不存在该单词
                return false;
        }
        return true;
    }
};

上面代码超时了,因为这个例子:
在这里插入图片描述

解决:

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> res;
        int w_size=words.size();
        int item_size=words[0].size();
        int len=w_size*item_size;
        map<string,int> words_map;
        for(int i=0;i<w_size;i++)//初始化
            words_map[words[i]]++;

        for(int i=0;i<s.size()-len+1;i++){//遍历
            if(find(s,words_map,i,len,item_size)){//串联子串
                res.push_back(i);//加入下标
                while( i+1<s.size()-len+1 && (s.substr(i+1,len)==s.substr(i,len))){//判断后移一个字符得到的串联子串 是否与前一个相等,原因:避免调用find函数进行不必要的迭代
                    i++;
                    res.push_back(i);
                }
            }
        }
        return res;
        
    }

    bool find(string s,map<string,int>words_map,int i,int len,int item_size){
        int index=i;
        for(i;i<index+len;i=i+item_size){
            string key=s.substr(i,item_size);
            if(words_map[key] > 0)//word匹配单词
                words_map[key]--;
            else //不存在该单词
                return false;
        }
        return true;
    }
};


在这里插入图片描述
很菜,做了好久…

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值