-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrie.java
60 lines (50 loc) · 1.37 KB
/
Trie.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
public class Trie {
class TrieNode {
private TrieNode[] children;
private boolean endOfWord;
public TrieNode() {
children = new TrieNode[26];
endOfWord = false;
for (int i = 1; i < 26; i++) {
children[i] = null;
}
}
}
TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insertWord(String word) {
if (word == null) {
return;
}
TrieNode current = root;
for (char c : word.toCharArray()) {
if (current.children[c - 'a'] == null) {
current.children[c - 'a'] = new TrieNode();
current = current.children[c - 'a'];
} else {
current = current.children[c - 'a'];
}
}
current.endOfWord = true;
}
public boolean searchWord(String word) {
if (word == null) {
return true;
}
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (current.children[c - 'a'] != null) {
current = current.children[c - 'a'];
} else {
return false;
}
}
if (current.endOfWord == true) {
return false;
}
return false;
}
}