forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
substring-with-concatenation-of-all-words.cpp
88 lines (80 loc) · 2.87 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Time: 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)
// Sliding window solution.
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
if (words.empty()) {
return {};
}
vector<int> result;
const int m = s.length(), n = words.size(), k = words.front().length();
if (m < n * k) {
return result;
}
unordered_map<string, int> lookup;
for (const auto& word : words) {
++lookup[word]; // Space: O(n * k)
}
for (int i = 0; i < k; ++i) { // Time: O(k)
unordered_map<string, int> tmp;
for (int j = i, left = i, count = 0; j <= m - k; j += k) { // Time: O(m / k)
const auto& str = s.substr(j, k); // Time: O(k)
if (lookup.count(str)) {
++tmp[str];
++count;
while (tmp[str] > lookup[str]) {
--tmp[s.substr(left, k)];
--count;
left += k;
}
if (count == n) {
result.emplace_back(left);
}
} else {
tmp.clear();
count = 0;
left = j + k;
}
}
}
return result;
}
};
// 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 Solution2 {
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;
}
};