题目:
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.
Example 1:
Input:
s = “barfoothefoobarman”,
words = [“foo”,”bar”]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are “barfoor” and “foobar” respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:
Input:
s = “wordgoodstudentgoodword”,
words = [“word”,”student”]
Output: []
题目意思:就是看word里面随便顺序连起来是不是出现过,然后将下标返回
解析:用map可以很好的解决这个问题,需要设置两个map,第一个map<string,int>word_count
记录每一个串在words中出现的次数 第二个map就是在遍历的时候需要记录words中每个单词出现的次数 map<string,int>counting;
//记录在查找过程中的次数 其实就是在主串S中对words中的每个单词进行遍历,如果没有出现则直接跳出,出现了则counting[ss]++,因为ss出现的次数可能大于words_count[ss],那么也是不合理的。
代码:
#include<iostream>
#include<set>
#include<vector>
#include<algorithm>
#include<string>
#include<map>
using namespace std;
vector<int> findSubstring(string s, vector<string>& words)
{
vector<int>ans;
if(s.length()==0||words.size()==0) return ans;
int i,j;
int s_len = s.length();
int l_size = words.size();
map<string,int>word_count; //记录每一个串在words中出现的次数
for(i=0;i<l_size;i++)
++word_count[words[i]];
int word_size = words[0].length();
map<string,int>counting; //记录在查找过程中的次数
for(i=0;i<=s_len-l_size*word_size;i++)
{
counting.clear();
for(j=0;j<l_size;j++)
{
string ss = s.substr(i+j*word_size,word_size); //对每个子串进行遍历
if(word_count.find(ss)!=word_count.end())
{
++counting[ss];
if(counting[ss]>word_count[ss]) break;
}
else break;
}
if(j==l_size) ans.push_back(i);
}
return ans;
}
int main()
{
string s = "wordgoodstudentgoodword";
initializer_list<string> lst = {"word","student"};
vector<string>words(lst);
vector<int>ans = findSubstring(s,words);
vector<int>::iterator iter = ans.begin();
for(;iter!=ans.end();iter++) cout<<*iter;
return 0;
}