File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ private TrieNode root = new TrieNode ();
3
+ private String result = "" ;
4
+
5
+ public String longestWord (String [] words ) {
6
+ for (String word : words ) {
7
+ root .insert (word );
8
+ }
9
+
10
+ dfs (root );
11
+ return result ;
12
+ }
13
+
14
+ private void dfs (TrieNode root ) {
15
+ if (root == null ) { return ; }
16
+
17
+ if (root .word != null ) {
18
+ if (root .word .length () > result .length ()) {
19
+ result = root .word ;
20
+ }
21
+ }
22
+
23
+ for (TrieNode child : root .children ) {
24
+ if (child != null && child .word != null ) {
25
+ dfs (child );
26
+ }
27
+ }
28
+ }
29
+
30
+ private class TrieNode {
31
+ private TrieNode [] children ;
32
+ private String word ;
33
+
34
+ public TrieNode () {
35
+ children = new TrieNode [26 ];
36
+ word = null ;
37
+ }
38
+
39
+ public void insert (String word ) {
40
+ TrieNode runner = root ;
41
+
42
+ for (char c : word .toCharArray ()) {
43
+ if (runner .children [c - 'a' ] == null ) {
44
+ runner .children [c - 'a' ] = new TrieNode ();
45
+ }
46
+
47
+ runner = runner .children [c - 'a' ];
48
+ }
49
+
50
+ runner .word = word ;
51
+ }
52
+ }
53
+ }
You can’t perform that action at this time.
0 commit comments