-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestWordInADictionaryUsingTrie.java
More file actions
54 lines (44 loc) · 1.01 KB
/
LongestWordInADictionaryUsingTrie.java
File metadata and controls
54 lines (44 loc) · 1.01 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
public class LongestWordInADictionaryUsingTrie {
class TrieNode {
TrieNode[] children = new TrieNode[26];
String word;
}
class Trie {
TrieNode root;
public Trie() {
root = new TrieNode();
root.word = "";
}
public void AddWord(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (node.children[c - 'a'] == null)
node.children[c - 'a'] = new TrieNode();
node = node.children[c - 'a'];
}
node.word = word;
}
}
public String LongestWord(String[] word) {
Trie trie = new Trie();
for (String w : word) {
trie.AddWord(w);
}
String[] result = new String[] { "" };
dfs(trie.root, result);
return result[0];
}
public void dfs(TrieNode node, String[] result) {
if (node.word == null)
return;
if (node.word.length() > result[0].length())
result[0] = node.word;
for (TrieNode child : node.children) {
if (child != null)
dfs(child, result);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}