-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC0720.cpp
More file actions
executable file
·58 lines (51 loc) · 1.25 KB
/
LC0720.cpp
File metadata and controls
executable file
·58 lines (51 loc) · 1.25 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
/*
Problem Statement: https://leetcode.com/problems/longest-word-in-dictionary/
Time: O(n • max_len)
Space: O(n • max_len)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
struct TrieNode {
int words, len;
unordered_map<char, TrieNode*> children;
TrieNode(): words(0), len(0) {}
};
struct Trie {
TrieNode* root;
Trie(vector<string>& words): root(new TrieNode()) {
for (string& word: words)
insert(word);
}
void insert(string& s) {
TrieNode* node = root;
for (char& c: s) {
if (!node->children.count(c))
node->children[c] = new TrieNode();
node->len = max((int) s.length(), node->len);
node = node->children[c];
}
node->words++;
node->len = max((int) s.length(), node->len);
}
};
class Solution {
public:
string longestWord(vector<string>& words) {
string longest, word;
Trie trie(words);
dfs(trie.root, word, longest);
return longest;
}
void dfs(TrieNode* node, string& word, string& longest) {
// optimization
if (node->len < longest.length())
return;
else if (word.length() > longest.length() || word.length() == longest.length() && word < longest)
longest = word;
for (auto& [c, u]: node->children)
if (u->words) {
word += c;
dfs(u, word, longest);
word.pop_back();
}
}
};