-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path208. Implement Trie (Prefix Tree)
47 lines (43 loc) · 1.18 KB
/
208. Implement Trie (Prefix Tree)
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
class Trie {
static Node root;
class Node{
boolean isend;
Node[] arr;
public Node(){
isend = false;
arr = new Node[26];
}
}
public Trie() {
root = new Node();
}
public void insert(String word) {
Node curr = root;
for(int i = 0 ; i < word.length() ; i++){
char ch = word.charAt(i);
if(curr.arr[ch - 'a'] == null){
curr.arr[ch - 'a'] = new Node();
}
curr = curr.arr[ch - 'a'];
}
curr.isend = true;
}
public boolean search(String word) {
Node curr = root;
for(int i = 0 ; i < word.length() ; i++){
char ch = word.charAt(i);
if(curr.arr[ch - 'a' ] == null) return false;
curr = curr.arr[ch - 'a'];
}
return curr.isend;
}
public boolean startsWith(String prefix) {
Node curr = root;
for(int i = 0 ; i < prefix.length() ; i++){
char ch = prefix.charAt(i);
if(curr.arr[ch - 'a'] == null) return false;
curr = curr.arr[ch - 'a'];
}
return true;
}
}