-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.java
More file actions
54 lines (49 loc) · 1.11 KB
/
Copy pathTrie.java
File metadata and controls
54 lines (49 loc) · 1.11 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
import java.util.*;
public class Trie
{
public TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String elem) {
TrieNode t = root;
for (int i=0; i<elem.length(); i++) {
if (elem.charAt(i) == '\'') {
// characte at i is a '
if (t.children[26] == null) {
t.children[26] = new TrieNode();
}
t = t.children[26];
}
else {
// character at i is a letter
if (t.children[(int)(elem.charAt(i)-'a')] == null) {
t.children[(int)(elem.charAt(i)-'a')] = new TrieNode();
}
t = t.children[(int)(elem.charAt(i)-'a')];
}
}
t.isEnd = true;
// search until the last word in elem and make isEnd to true
}
public boolean search(String elem) {
TrieNode t = root;
for (int i=0; i<elem.length(); i++) {
if (elem.charAt(i) == '\'') {
if (t.children[26] == null) {
// there's no '
return false;
}
t = t.children[26];
}
else {
if (t.children[(int)(elem.charAt(i)-'a')] == null) {
// there's no the specific character
return false;
}
t = t.children[(int)(elem.charAt(i)-'a')];
}
}
return t.isEnd;
}
}