-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.cpp
55 lines (52 loc) · 1.44 KB
/
Solution.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
class Trie {
public:
void insert(string& w, int i) {
Trie* node = this;
for (int j = 0; j < w.size(); ++j) {
int idx = w[j] - 'a';
if (!node->children[idx]) {
node->children[idx] = new Trie();
}
node = node->children[idx];
if (node->v.size() < 3) {
node->v.push_back(i);
}
}
}
vector<vector<int>> search(string& w) {
Trie* node = this;
int n = w.size();
vector<vector<int>> ans(n);
for (int i = 0; i < w.size(); ++i) {
int idx = w[i] - 'a';
if (!node->children[idx]) {
break;
}
node = node->children[idx];
ans[i] = move(node->v);
}
return ans;
}
private:
vector<Trie*> children = vector<Trie*>(26);
vector<int> v;
};
class Solution {
public:
vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {
sort(products.begin(), products.end());
Trie* trie = new Trie();
for (int i = 0; i < products.size(); ++i) {
trie->insert(products[i], i);
}
vector<vector<string>> ans;
for (auto& v : trie->search(searchWord)) {
vector<string> t;
for (int i : v) {
t.push_back(products[i]);
}
ans.push_back(move(t));
}
return ans;
}
};