-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathlongest-common-suffix-queries.cpp
63 lines (56 loc) · 1.66 KB
/
longest-common-suffix-queries.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
// Time: O((n + q) * l)
// Space: O(t)
// trie
class Solution {
private:
class Trie {
public:
Trie() {
new_node();
}
void add(int i, const string& w) {
int curr = 0;
mns_[curr] = min(mns_[curr], {size(w), i});
for (int j = size(w) - 1; j >= 0; --j) {
const int x = w[j] - 'a';
if (nodes_[curr][x] == -1) {
nodes_[curr][x] = new_node();
}
curr = nodes_[curr][x];
mns_[curr] = min(mns_[curr], {size(w), i});
}
}
int query(const string& w) {
int curr = 0;
for (int j = size(w) - 1; j >= 0; --j) {
const int x = w[j] - 'a';
if (nodes_[curr][x] == -1) {
break;
}
curr = nodes_[curr][x];
}
return mns_[curr].second;
}
private:
int new_node() {
static const int INF = numeric_limits<int>::max();
nodes_.emplace_back(26, -1);
mns_.emplace_back(INF, INF);
return size(nodes_) - 1;
}
vector<vector<int>> nodes_;
vector<pair<int, int>> mns_;
};
public:
vector<int> stringIndices(vector<string>& wordsContainer, vector<string>& wordsQuery) {
Trie trie;
for (int i = 0; i < size(wordsContainer); ++i) {
trie.add(i, wordsContainer[i]);
}
vector<int> result(size(wordsQuery));
for (int i = 0; i < size(wordsQuery); ++i) {
result[i] = trie.query(wordsQuery[i]);
}
return result;
}
};