30、Substring with Concatenation of All Words
子字符串连接的单词
现有一组长度相等的字符串words,要在原字符串中找出正好包含words中所有字符串的子字符串的起始位置。
例子:
输入: s = “barfoothefoobarman”, words = [“foo”, “bar”]输出: [0, 9]
分析:
(unordered_map<关键字,值>无序map类型)
1.这道题是寻找子字符串的深化版本,寻找的子字符串是由多个等长的字符串连接在一起的,难点就在于子字符串之间没有先后顺序。
2.就是我们需要确保每一个子字符串都只出现了一次,所以我们需要两个unordered_map<string,int>来存储字符串和他的出现次数,一个做为对比模板,一个做为查找计数。
3.迭代原字符串,每当找到一个同words中的字符串时,就进入循环类比接下来同样长度的字符串中是否与words相同且不重复,达成则记录迭代,否则break。
代码:
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
unordered_map<string,int> compare;//比较模板
for(string w:words)
compare[w]++;
int n=s.length(),num=words.size(),len=words[0].length();
vector<int> res;
for(int i=0;i<=n-num*len+1;i++)
{
unordered_map<string,int>counts;//计数
int j=0;
for(;j<num;j++)
{
string word=s.substr(i+j*len,len);//复制
if(compare.find(word)!=compare.end())
{
counts[word]++;
if(counts[word]>compare[word])
break;
}
else break;
}
if(j==num)res.push_back(i);
}
return res;
}
};