-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path#1268. Search Suggestions System.cpp
More file actions
91 lines (78 loc) · 2.09 KB
/
#1268. Search Suggestions System.cpp
File metadata and controls
91 lines (78 loc) · 2.09 KB
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
89
90
91
class Node {
public:
vector<Node*> links;
bool end;
Node() {
links.resize(26, nullptr);
end = false;
}
bool containsKey(char ch) {
return links[ch - 'a'] != nullptr;
}
Node* next(char ch) {
return links[ch - 'a'];
}
void put(char ch, Node* node) {
links[ch - 'a'] = node;
}
};
class Trie {
public:
Node* root;
Trie() {
root = new Node();
}
void insert(const string& word) {
Node* node = root;
for (char ch : word) {
if (!node->containsKey(ch)) {
node->put(ch, new Node());
}
node = node->next(ch);
}
node->end = true;
}
// DFS helper to collect suggestions
void dfs(Node* node, string& curr, vector<string>& ans) {
if (!node || ans.size() == 3) return;
if (node->end) ans.push_back(curr);
if (ans.size() == 3) return;
for (int i = 0; i < 26; i++) {
if (node->links[i]) {
curr.push_back('a' + i);
dfs(node->links[i], curr, ans);
curr.pop_back(); // backtrack
if (ans.size() == 3) return; // stop early
}
}
}
vector<string> find(const string& prefix) {
Node* node = root;
for (char ch : prefix) {
if (!node->containsKey(ch)) return {}; // no such prefix
node = node->next(ch);
}
vector<string> ans;
string curr = prefix;
dfs(node, curr, ans);
return ans;
}
};
class Solution {
public:
vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {
// Step 1: Insert all products
Trie trie;
for (string& prod : products) {
trie.insert(prod);
}
// Step 2: For each prefix of searchWord, collect top 3 suggestions
vector<vector<string>> result;
string prefix = "";
for (char ch : searchWord) {
prefix += ch;
result.push_back(trie.find(prefix));
}
return result;
}
};