-
Notifications
You must be signed in to change notification settings - Fork 0
/
Implement Trie.java
63 lines (55 loc) · 1.22 KB
/
Implement 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
61
62
63
class Trie {
Node head;
public Trie() {
head = new Node('/', false);
}
public void insert(String word) {
Node cur = head;
for (char ch : word.toCharArray()) {
if (cur.arr[ch - 'a'] == null) {
cur.arr[ch - 'a'] = new Node(ch, false);
}
cur = cur.arr[ch - 'a'];
}
cur.isEndOfWord = true;
}
public boolean search(String word) {
Node cur = head;
for (char ch : word.toCharArray()) {
if (cur.arr[ch - 'a'] == null) {
return false;
}
cur = cur.arr[ch - 'a'];
}
if (cur.isEndOfWord) {
return true;
}
return false;
}
public boolean startsWith(String prefix) {
Node cur = head;
for (char ch : prefix.toCharArray()) {
if (cur.arr[ch - 'a'] == null) {
return false;
}
cur = cur.arr[ch - 'a'];
}
return true;
}
}
class Node {
char val;
boolean isEndOfWord;
Node[] arr = new Node[26];
Node(char val, boolean isEndOfWord) {
this.val = val;
this.isEndOfWord = isEndOfWord;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/