代码
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> ans;
if (words.empty()) return ans;
int n = s.size(), m = words.size(), w= words[0].size();
unordered_map<string, int> map;
for (auto word: words) map[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 + m * w) {
auto word = s.substr(j - m * w, w);
wd[word]--;
if (wd[word] < map[word]) cnt--;
}
auto word = s.substr(j, w);
wd[word]++;
if (wd[word] <= map[word]) cnt++;
if (cnt == m) ans.push_back(j - (m - 1) * w);
}
}
return ans;
}
};