给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。
示例 1:
输入:
s = "barfoothefoobarman",
words = ["foo","bar"]
输出:[0,9]
解释:
从索引 0 和 9 开始的子串分别是 "barfoo" 和 "foobar" 。
输出的顺序不重要, [9,0] 也是有效答案。
示例 2:
输入:
s = "wordgoodgoodgoodbestword",
words = ["word","good","best","word"]
输出:[]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
这题就是维护哈希表记录单词与出现次数的关系,然后枚举滑动窗口起点,记录窗口内单词出现情况,然后和上面的表比对
- 哈希表 hash 记录给定单词 words 中单词出现的次数
- 滑动窗口长度就是words所有单词长度的加和,然后开始滑动窗口右移,将整个窗口分为:【每块长度与words中单词长度相同】的若干块,每一块就是一个单词
- 维护哈希表 h 记录单词出现次数,然后和 hash 中的次数比对,如果全部符合,那么就是答案
代码
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words)
{
vector<int> ans;
if(words.size()==0) return ans;
unordered_map<string, int> hash;
int len=words[0].length(), wlen=words[0].length()*words.size();
// 记录words中单词出现次数
for(int i=0; i<words.size(); i++) hash[words[i]]++;
for(int i=0; i+wlen<=s.length(); i++)
{
if(hash[s.substr(i, len)]==0) continue;
unordered_map<string, int> h;
// 记录窗口内单词出现次数
for(int j=0; j<words.size(); j++)
h[s.substr(i+j*len, len)]++;
// 和hash中出现次数比对
int cnt = 0;
for(auto it=hash.begin(); it!=hash.end(); it++)
if(h[it->first]==it->second) cnt++;
else break;
if(cnt==hash.size()) ans.push_back(i);
}
return ans;
}
};