forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
substring-with-concatenation-of-all-words.cpp
39 lines (35 loc) · 1.32 KB
/
substring-with-concatenation-of-all-words.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
37
38
39
// Time: O((m - n * k) * n * k) ~ O(m * n * k), m is the length of the string,
// n is the size of the dictionary,
// k is the length of each word
// Space: O(n * k)
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
const auto word_length = words.front().length();
const auto cat_length = word_length * words.size();
vector<int> result;
if (s.length() < cat_length) {
return result;
}
unordered_map<string, int> wordCount;
for (const auto & word : words) {
++wordCount[word];
}
for (auto it = s.begin(); it != prev(s.end(), cat_length - 1); ++it) {
unordered_map<string, int> unused(wordCount);
for (auto jt = it; jt != next(it, cat_length); jt += word_length) {
auto pos = unused.find(string(jt, next(jt, word_length)));
if (pos == unused.end()) {
break;
}
if (--pos->second == 0) {
unused.erase(pos);
}
}
if (unused.empty()) {
result.emplace_back(distance(s.begin(), it));
}
}
return result;
}
};