leetcode 30. Substring with Concatenation of All Words

题意

在串s中找一个连续的子串,要求words数组中的单词每个都要出现一次(重复的单词要多次出现),返回子串的起始下标

题解

用map保存单词及其出现的次数,然后枚举s的各个起始下标,找words中的各个单词。(如何找到单词且其剩余数目大于0,则继续查找下一个单词)

代码

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {

        int slen = s.length();
        int sublen = words[0].length();
        int size = words.size();
        map<string, int> word_count;
        for(int i = 0; i < size; i++)
        {
            if(!word_count.count(words[i]))
                word_count[words[i]] = 1;
            else
                word_count[words[i]]++;
        }

        vector<int> result;

        for (int i = 0; i < slen; i++)
        {
            int count = 0;
            int j = i;
            map<string,int> temp(word_count);
            if(j > slen - size * sublen)
                break;
            while (j <= slen - sublen)
            {
                string substr = s.substr(j, sublen);

                if (temp.count(substr) && temp[substr] > 0) // if count>0
                {
                    temp[substr]--;
                    j += sublen;
                    count ++;
                }
                else
                    break;


            }
            if (count == size)
                result.push_back(i);

        }
        return result;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值