forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_720.java
61 lines (56 loc) · 1.96 KB
/
_720.java
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
package com.fishercoder.solutions;
public class _720 {
public static class Solution1 {
public String longestWord(String[] words) {
TrieNode root = buildTrie(words);
return findLongestWord(root, words);
}
private String findLongestWord(TrieNode root, String[] words) {
String longestWord = "";
for (String word : words) {
if (longestWord.length() > word.length() || (longestWord.length() == word.length() && (longestWord.compareToIgnoreCase(word) < 0))) {
continue;
}
TrieNode tmp = root;
boolean validWord = true;
for (char c : word.toCharArray()) {
if (tmp.children[c - 'a'] != null) {
tmp = tmp.children[c - 'a'];
if (!tmp.isWord) {
validWord = false;
break;
}
}
}
if (validWord) {
longestWord = word;
}
}
return longestWord;
}
private TrieNode buildTrie(String[] words) {
TrieNode root = new TrieNode(' ');
for (String word : words) {
TrieNode tmp = root;
for (char c : word.toCharArray()) {
if (tmp.children[c - 'a'] == null) {
tmp.children[c - 'a'] = new TrieNode(c);
}
tmp = tmp.children[c - 'a'];
}
tmp.isWord = true;
}
return root;
}
class TrieNode {
char val;
boolean isWord;
TrieNode[] children;
public TrieNode(char val) {
this.val = val;
this.isWord = false;
this.children = new TrieNode[26];
}
}
}
}