-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC1268.cpp
More file actions
executable file
·80 lines (68 loc) · 1.71 KB
/
LC1268.cpp
File metadata and controls
executable file
·80 lines (68 loc) · 1.71 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
/*
Problem Statement: https://leetcode.com/problems/search-suggestions-system/
Time: O((m + n) • max_len)
Space: O(m • n • max_len)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
struct TrieNode {
int words;
vector<TrieNode*> children;
TrieNode() : words(0), children(26) {}
};
struct Trie {
TrieNode* root;
Trie(vector<string>& words) : root(new TrieNode()) {
for (string& word: words)
insert(word);
}
void insert(string& word) {
TrieNode* node = root;
for (char& c: word) {
if (!node->children[c - 'a'])
node->children[c - 'a'] = new TrieNode();
node = node->children[c - 'a'];
}
node->words++;
}
TrieNode* search(char c, TrieNode* node) {
if (!node || !node->children[c - 'a'])
return nullptr;
return node->children[c - 'a'];
}
vector<string> get_suggestions(string path, TrieNode* node) {
vector<string> res;
stack<TrieNode*> st;
// helper function
function<void(TrieNode*)> dfs = [&](TrieNode* node) {
if (res.size() == 3)
return;
else if (node->words)
res.push_back(path);
for (char c = 'a'; c <= 'z'; c++)
if (node->children[c - 'a']) {
path += c;
dfs(node->children[c - 'a']);
path.pop_back();
}
};
if (node)
dfs(node);
return res;
}
};
class Solution {
public:
vector<vector<string>> suggestedProducts(vector<string>& products, string& searchWord) {
int m = products.size(), n = searchWord.length();
string word;
Trie trie(products);
TrieNode* node = trie.root;
vector<vector<string>> suggestions(n);
for (int i = 0; i < n; i++) {
word += searchWord[i];
node = trie.search(searchWord[i], node);
suggestions[i] = trie.get_suggestions(word, node);
}
return suggestions;
}
};