File tree 1 file changed +47
-0
lines changed
longest-word-in-dictionary
1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ struct TrieNode {
2
+ bool isEnd;
3
+ string word;
4
+ TrieNode* child[26 ];
5
+ };
6
+
7
+ void insert (TrieNode* root, string str){
8
+ TrieNode* curr = root;
9
+ for (auto c: str){
10
+ int idx = c - ' a' ;
11
+ if (curr->child [idx] == NULL )
12
+ curr->child [idx] = new TrieNode ();
13
+ curr = curr->child [idx];
14
+ }
15
+
16
+ curr->isEnd = true ;
17
+ curr->word = str;
18
+ }
19
+
20
+ void dfs (TrieNode* root, string& res){
21
+ if (root == NULL )
22
+ return ;
23
+
24
+ if (root->isEnd ){
25
+ res = root->word .size () > res.size () ? root->word : res;
26
+ }
27
+
28
+ for (int i = 0 ; i < 26 ; i++){
29
+ if (root->child [i] != NULL and root->child [i]->isEnd )
30
+ dfs (root->child [i], res);
31
+ }
32
+ }
33
+
34
+ class Solution {
35
+ TrieNode* root;
36
+ public:
37
+ string longestWord (vector<string>& words) {
38
+ root = new TrieNode ();
39
+ for (string w: words){
40
+ insert (root, w);
41
+ }
42
+
43
+ string res = " " ;
44
+ dfs (root, res);
45
+ return res;
46
+ }
47
+ };
You can’t perform that action at this time.
0 commit comments