您的位置:首页 > 其它

leetcode30---Substring with Concatenation of All Words

2015-12-22 15:29 405 查看
问题描述:

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode unordered map