-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathPrefixTrie.java
71 lines (57 loc) · 1.68 KB
/
PrefixTrie.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
62
63
64
65
66
67
68
69
70
71
package trie;
public class PrefixTrie {
class Node {
char character;
boolean endOfWord;
Node[] offspring = new Node[26];
Node() {}
Node(char ch) {
this.character = ch;
}
}
private final Node rootNode;
public PrefixTrie() {
rootNode = new Node();
rootNode.character = ' ';
}
public void insert(String term) {
Node current = rootNode;
for (char ch : term.toCharArray()) {
if (current.offspring[ch - 'a'] == null) {
current.offspring[ch - 'a'] = new Node(ch);
}
current = current.offspring[ch - 'a'];
}
current.endOfWord = true;
}
public boolean search(String term) {
Node current = rootNode;
for (char ch : term.toCharArray()) {
if (current.offspring[ch - 'a'] == null) {
return false;
}
current = current.offspring[ch - 'a'];
}
return current.endOfWord;
}
public boolean startsWith(String initial) {
Node current = rootNode;
for (char ch : initial.toCharArray()) {
if (current.offspring[ch - 'a'] == null) {
return false;
}
current = current.offspring[ch - 'a'];
}
return true;
}
public static void main(String[] args) {
PrefixTrie tree = new PrefixTrie();
tree.insert("apple");
assert tree.search("apple");
assert !tree.search("app");
assert tree.startsWith("app");
tree.insert("app");
assert tree.search("app");
System.out.println("All tests passed!");
}
}