forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest-word-in-dictionary.cpp
66 lines (59 loc) · 1.74 KB
/
longest-word-in-dictionary.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
// Time: O(n), n is the total sum of the lengths of words
// Space: O(t), t is the number of nodes in trie
class Solution {
public:
string longestWord(vector<string>& words) {
TrieNode trie;
for (int i = 0; i < words.size(); ++i) {
trie.Insert(words[i], i);
}
// DFS
stack<TrieNode *> stk;
for (const auto& node : trie.leaves) {
if (node) {
stk.emplace(node);
}
}
string result;
while (!stk.empty()) {
const auto curr = stk.top(); stk.pop();
if (curr->isString) {
const auto& word = words[curr->val];
if (word.size() > result.size() || (word.size() == result.size() && word < result)) {
result = word;
}
for (const auto& node : curr->leaves) {
if (node) {
stk.emplace(node);
}
}
}
}
return result;
}
private:
struct TrieNode {
bool isString;
int val;
vector<TrieNode *> leaves;
TrieNode() : isString{false}, val{0}, leaves(26) {}
void Insert(const string& s, const int i) {
auto* p = this;
for (const auto& c : s) {
if (!p->leaves[c - 'a']) {
p->leaves[c - 'a'] = new TrieNode;
}
p = p->leaves[c - 'a'];
}
p->isString = true;
p->val = i;
}
~TrieNode() {
for (auto& node : leaves) {
if (node) {
delete node;
}
}
}
};
};