forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0208-implement-trie-prefix-tree.java
56 lines (46 loc) · 1.23 KB
/
0208-implement-trie-prefix-tree.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
class Trie {
Node root;
public Trie() {
root = new Node('\0'); //dummy node
}
public void insert(String word) {
Node curr = root;
for (char x : word.toCharArray()) {
if (curr.children[x - 'a'] == null) {
curr.children[x - 'a'] = new Node(x);
}
curr = curr.children[x - 'a'];
}
curr.isWord = true;
}
public boolean search(String word) {
Node res = getLast(word);
return (res != null && res.isWord);
}
//helper method
public Node getLast(String word) {
Node curr = root;
for (char x : word.toCharArray()) {
if (curr.children[x - 'a'] == null) {
return null;
}
curr = curr.children[x - 'a'];
}
return curr;
}
public boolean startsWith(String prefix) {
Node res = getLast(prefix);
if (res == null) return false;
return true;
}
class Node {
private char value;
private boolean isWord;
private Node[] children;
public Node(char val) {
this.value = val;
this.isWord = false;
this.children = new Node[26];
}
}
}