forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest-word-with-all-prefixes.cpp
97 lines (88 loc) · 2.68 KB
/
longest-word-with-all-prefixes.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
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
92
93
94
95
96
97
// Time: O(n)
// Space: O(t), t is the number of nodes in trie
class Solution {
private:
class TrieNode {
public:
int idx = -1;
unordered_map<char, unique_ptr<TrieNode>> leaves;
void Insert(int i, const string& s) {
auto p = this;
for (const auto& c : s) {
if (!p->leaves.count(c)) {
p->leaves[c] = make_unique<TrieNode>();
}
p = p->leaves[c].get();
}
p->idx = i;
}
};
public:
string longestWord(vector<string>& words) {
auto trie = make_unique<TrieNode>();
for (int i = 0; i < size(words); ++i) {
trie->Insert(i, words[i]);
}
return iter_dfs(words, trie.get());
}
private:
string iter_dfs(const vector<string>& words, TrieNode *node) {
int result = -1;
vector<TrieNode *> stk = {node};
while (!empty(stk)) {
const auto node = stk.back(); stk.pop_back();
if (result == -1 || size(words[node->idx]) > size(words[result])) {
result = node->idx;
}
for (char c = 'z'; c >= 'a'; --c) {
if (!node->leaves.count(c) || node->leaves[c]->idx == -1) {
continue;
}
stk.emplace_back(node->leaves[c].get());
}
}
return result != -1 ? words[result] : "";
}
};
// Time: O(n)
// Space: O(t), t is the number of nodes in trie
class Solution2 {
private:
class TrieNode {
public:
int idx = -1;
unordered_map<char, unique_ptr<TrieNode>> leaves;
void Insert(int i, const string& s) {
auto p = this;
for (const auto& c : s) {
if (!p->leaves.count(c)) {
p->leaves[c] = make_unique<TrieNode>();
}
p = p->leaves[c].get();
}
p->idx = i;
}
};
public:
string longestWord(vector<string>& words) {
auto trie = make_unique<TrieNode>();
for (int i = 0; i < size(words); ++i) {
trie->Insert(i, words[i]);
}
int result = -1;
dfs(words, trie.get(), &result);
return result != -1 ? words[result] : "";
}
private:
void dfs(const vector<string>& words, TrieNode *node, int *result) {
if (*result == -1 || size(words[node->idx]) > size(words[*result])) {
*result = node->idx;
}
for (char c = 'a'; c <= 'z'; ++c) {
if (!node->leaves.count(c) || node->leaves[c]->idx == -1) {
continue;
}
dfs(words, node->leaves[c].get(), result);
}
}
};