-
Notifications
You must be signed in to change notification settings - Fork 1
/
30.串联所有单词的子串.cpp
37 lines (33 loc) · 1017 Bytes
/
30.串联所有单词的子串.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
* @lc app=leetcode.cn id=30 lang=cpp
*
* [30] 串联所有单词的子串
*/
// @lc code=start
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 + m * w) {
auto word = s.substr(j - m * w, w);
wd[word]--;
if (wd[word] < tot[word]) cnt--;
}
auto 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;
}
};
// @lc code=end