leetcode30---Substring with Concatenation of All Words

问题描述:

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

For example, given:

s: "barfoothefoobarman"
words: ["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).

问题求解:

用到哈希map:unordered_map.
(1)

unordered_map<string,int> num;用来记录words中每一个word,及其出现的次数
num[word].

(2)

unordered_map<string, int> match;//记录与word匹配的sword,及其匹配次数

(3)依次检查每一个可能的起点i

如果没有匹配成功,或者word匹配次数超过了words中该word的数量,跳到下一个i;
如果成功完成此次检查,则i即为满足的起点,将i放入res;

代码:

#include <iostream>
//#include<cstring>
#include<vector>
#include<unordered_map>
using namespace std;

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        unordered_map<string,int> num;
        //for(string word:words)
            //num[word]++;//num[word]记录words中每一个word出现的次数
        for(unsigned int i=0;i<words.size();i++)
        {
            num[words[i]]++;//num[word]记录words中每一个word出现的次数
        }
        int slen=s.size();
        int wordslen=words.size();
        int wordlen=words[0].size();//每个word长度相同
        vector<int> res;//存储结果
        for(int i=0;i<slen-wordslen*wordlen+1;i++)
        {//slen-wordslen*wordlen为s与words进行最后一个匹配的起点
            int j;
            unordered_map<string, int> match;//记录与word匹配的sword,及其匹配次数
            for(j=0;j<wordslen;j++)
            {//对words中的每一个word而言
                //以i+j*wordlen为起点,在s中找到与每个word长度一样的sword
                string sword=s.substr(i+j*wordlen, wordlen);
                if(num.find(sword) != num.end())
                {//如果当前sword匹配
                    match[sword]++;
                    //防止类似情况s="abcdcdef",words=["cd","ef"],sword="cd"
                    if(match[sword] > num[sword]) break;
                }
                //如果不匹配,跳到下一个i起点
                else break;
            }
            //如果成功完成检测,当前起点i符合
            if(j==wordslen) res.push_back(i);
        }
        return res;
    }
};
int main()
{
    Solution s;
    vector<int> res;//存储结果
    string str="barfoothefoobarman";
    vector<string> words={"foo","bar"};
    res=s.findSubstring(str, words);
    for(unsigned int i=0;i<res.size();i++)
    {
        cout<<res[i]<<" ";
    }
    cout<<endl;
    return 0;
}

结果:

0 9

Process returned 0 (0x0)   execution time : 0.208 s
Press any key to continue.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值