-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathDictionaryTrie.java
More file actions
55 lines (45 loc) · 1.17 KB
/
DictionaryTrie.java
File metadata and controls
55 lines (45 loc) · 1.17 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
55
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
public class DictionaryTrie {
class Node {
public char value;
public Node[] children = null;
public ArrayList<String> wordsAtPosition;
public Node() {
value = '!';
wordsAtPosition = new ArrayList<String>();
}
public Node(char ch) {
value = ch;
wordsAtPosition = new ArrayList<String>();
}
}
public static Node root;
public DictionaryTrie() {
root = new Node('!');
}
public Node getRootNode() {
return root;
}
public void populateTrieFromSet(HashSet<String> words) {
Iterator<String> itr = words.iterator();
Node runner = root;
while (itr.hasNext()) {
String tempString = itr.next();
runner = root;
for (int i = 0; i < tempString.length(); ++i) {
int index = tempString.charAt(i);
if (runner.children == null)
runner.children = new Node[256];
if (runner.children[index] == null)
runner.children[index] = new Node(tempString.charAt(i));
runner = runner.children[index];
// insert the word into the last node position
if (i == tempString.length() - 1) {
runner.wordsAtPosition.add(tempString);
}
}
}
}
}