/
WordAutocompletion.java
41 lines (31 loc) · 1.17 KB
/
WordAutocompletion.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
package com.anthonynsimon.algorithms.trees;
import com.anthonynsimon.datastructures.Trie;
import com.anthonynsimon.datastructures.util.TrieNode;
import java.util.ArrayList;
public final class WordAutocompletion extends Trie<String> {
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public WordAutocompletion() {
super();
}
public String[] autocomplete(String prefix) {
ArrayList<String> results = new ArrayList<>();
TrieNode<String> lastChar = getNodeAtLast(prefix);
depthFirstSearch(prefix, lastChar, results);
return results.toArray(new String[]{});
}
private void depthFirstSearch(String prefix, TrieNode<String> node, ArrayList<String> results) {
if (node == null) {
return;
}
for (int i = 0; i < node.getChildren().length; i++) {
TrieNode<String> child = node.getChild(i);
if (child != null) {
String str = prefix + ALPHABET.charAt(i);
if (child.getValue() != null) {
results.add(str);
}
depthFirstSearch(str, child, results);
}
}
}
}