思路
滑动窗口
将字符串s分为多个长度的w(每个单词长度)的子区间,
使用hash保存words中每个单词的个数
再开一个hash保存遍历时的每个单词
用cnt来记录子串中合法的单词个数
每次遍历,和m*w之前的那个单词比较,如果单词在第一个开的hash中,就减去那个单词
判断新的单词是不是保存在hash里且不超过words中的那个单词的个数,如果是,代表这个单词为合法单词,cnt+1,
当cnt和m(words.size)相等时,即为一组结果,将j-(m-1)*w存入结果集
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> res;
if(words.empty()) return res;
int n = s.size(), m = words.size(), w = words[0].size();
unordered_map<string,int> tot;
for(auto& word:words) tot[word]++;
for(int i = 0; i < w; i++){
unordered_map<string,int> wd;
int cnt = 0;
for(int j = i;j + w <= n;j+=w){
if(j >= i + w * m){
string word = s.substr(j - m * w, w);
wd[word]--;
if(wd[word]<tot[word])cnt--;
}
string word = s.substr(j,w);
wd[word]++;
if(wd[word] <= tot[word]) cnt++;
if(cnt == m) res.push_back(j-(m-1)*w);
}
}
return res;
}
};