Skip to content

Commit a76ba93

Browse files
authored
Create longest-common-suffix-queries.cpp
1 parent c18dab5 commit a76ba93

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

C++/longest-common-suffix-queries.cpp

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// Time: O((n + q) * l)
2+
// Space: O(t)
3+
4+
// trie
5+
class Solution {
6+
private:
7+
class Trie {
8+
public:
9+
Trie() {
10+
new_node();
11+
}
12+
13+
void add(int i, const string& w) {
14+
int curr = 0;
15+
mns_[curr] = min(mns_[curr], {size(w), i});
16+
for (int j = size(w) - 1; j >= 0; --j) {
17+
const int x = w[j] - 'a';
18+
if (nodes_[curr][x] == -1) {
19+
nodes_[curr][x] = new_node();
20+
}
21+
curr = nodes_[curr][x];
22+
mns_[curr] = min(mns_[curr], {size(w), i});
23+
}
24+
}
25+
26+
int query(const string& w) {
27+
int curr = 0;
28+
for (int j = size(w) - 1; j >= 0; --j) {
29+
const int x = w[j] - 'a';
30+
if (nodes_[curr][x] == -1) {
31+
break;
32+
}
33+
curr = nodes_[curr][x];
34+
}
35+
return mns_[curr].second;
36+
}
37+
38+
private:
39+
int new_node() {
40+
static const int INF = numeric_limits<int>::max();
41+
42+
nodes_.emplace_back(26, -1);
43+
mns_.emplace_back(INF, INF);
44+
return size(nodes_) - 1;
45+
}
46+
47+
vector<vector<int>> nodes_;
48+
vector<pair<int, int>> mns_;
49+
};
50+
51+
public:
52+
vector<int> stringIndices(vector<string>& wordsContainer, vector<string>& wordsQuery) {
53+
Trie trie;
54+
for (int i = 0; i < size(wordsContainer); ++i) {
55+
trie.add(i, wordsContainer[i]);
56+
}
57+
vector<int> result(size(wordsQuery));
58+
for (int i = 0; i < size(wordsQuery); ++i) {
59+
result[i] = trie.query(wordsQuery[i]);
60+
}
61+
return result;
62+
}
63+
};

0 commit comments

Comments
 (0)