题目描述
给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。
示例 1:
输入: s = "barfoothefoobarman", words = ["foo","bar"] 输出:[0,9] 解释: 从索引 0 和 9 开始的子串分别是 "barfoor" 和 "foobar" 。 输出的顺序不重要, [9,0] 也是有效答案。
示例 2:
输入:
s = "wordgoodgoodgoodbestword",
words = ["word","good","best","word"]
输出:[]
问题分析
先将words数组中的字符串都保存到一个哈希表umap1里。然后计算字符串s和words数组的大小,记为slen和len。后面遍历字符串s时,是间隔len来遍历的。记left为s中匹配的部分的起始位置。count为当前已经匹配了多少个词。遍历到的词如果是umap1中有的词,那么就存到哈希表umap2中,并且count加1,此时判断如果umap2中该词的个数已经大于umap1中该词的个数,那么说明该从left开始往后将词去掉,直到把重复的那个词去掉一个为止。在这个过程中,每去掉一个词,就把它从哈希表umap2中去掉,并且count减1。退出while循环后,umap2中刚才重复那个词的个数就等于umap1中该词的个数了。并且此时left的位置就是去掉的那个重复词的后一位置。count也是从left开始的词数量。此时判断如果count等于words数组的大小,说明已经找到一个匹配了,并将left加到ans数组后。由于匹配长度是固定的,所以匹配部分的第一个词在接下来的下一次遍历时就肯定没用了,所以应该将它从哈希表umap2中删去,且count减1,并且将left向后移动一个词的位置,然后准备进入下一个词的遍历。回过头说刚才如果遍历到的词是umap1中没有的词,那么说明从当前词包括往前的词就都没用了,接下来要从下一个词开始遍历,将哈希表umap2清空并将count置0,并将left向后移动len位。所有的都遍历结束后,返回数组ans。
代码实现
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
if(words.empty() || s.empty())
return {};
vector<int> ans;
unordered_map<string, int> umap1;
unordered_map<string, int> umap2;
int count = 0;
int left = 0;
for(string str : words)
++umap1[str];
int len = words[0].size();
int slen = s.size();
for(int i = 0; i < len; i++){
left = i;
count = 0;
umap2.clear();
for(int j = i; j <= slen - len; j += len){
string temp = s.substr(j, len);
if(umap1.count(temp)){
umap2[temp]++;
count++;
while(umap2[temp] > umap1[temp]){
string temp2 = s.substr(left, len);
--umap2[temp2];
--count;
left += len;
}
if(count == words.size()){
ans.push_back(left);
--umap2[s.substr(left, len)];
--count;
left += len;
}
}
else{
umap2.clear();
count = 0;
left = j + len;
}
}
}
return ans;
}
};