-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrieDictionary.java
59 lines (50 loc) · 1.76 KB
/
TrieDictionary.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
class Solution {
private class Trie {
private class TrieNode {
Map<Character, TrieNode> edges;
boolean isWordEnd;
TrieNode() {
this.edges = new HashMap<>();
isWordEnd = false;
}
}
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode currentNode = root;
for (char c : word.toCharArray()) {
if (!currentNode.edges.containsKey(c))
currentNode.edges.put(c, new TrieNode());
currentNode = currentNode.edges.get(c);
}
currentNode.isWordEnd = true;
}
public boolean canBeBuilt(String word) {
TrieNode currentNode = root;
for (char c : word.toCharArray()) {
if (!currentNode.edges.containsKey(c))
return false;
currentNode = currentNode.edges.get(c);
if (!currentNode.isWordEnd)
return false;
}
return true;
}
}
public String longestWord(String[] words) {
if (words == null || words.length == 0)
return null;
Trie trie = new Trie();
for (String word : words)
trie.insert(word);
String answer = null;
for (String word : words)
if (trie.canBeBuilt(word))
if (answer == null || answer.length() < word.length() || (answer.length() == word.length() && word.compareTo(answer) < 0)) {
answer = word;
}
return answer;
}
}