-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTriePrefixTree.java
57 lines (50 loc) · 1.5 KB
/
TriePrefixTree.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
public class TriePrefixTree {
/**
* https://leetcode.com/problems/implement-trie-prefix-tree/description/
*/
class Trie {
private Node root;
public Trie() {
root = new Node('\0'); // dummy node for root
}
public void insert(String word) {
Node curr = root;
for (char c : word.toCharArray()) {
if (curr.children[c - 'a'] == null) {
curr.children[c - 'a'] = new Node(c);
}
curr = curr.children[c - 'a'];
}
curr.isLast = true;
}
public boolean search(String word) {
Node n = getLast(word);
return n != null && n.isLast;
}
public boolean startsWith(String prefix) {
Node n = getLast(prefix);
return n != null;
}
//helper for get last node
private Node getLast(String word) {
Node curr = root;
for (char c : word.toCharArray()) {
if (curr.children[c - 'a'] == null) {
return null;
}
curr = curr.children[c - 'a'];
}
return curr;
}
class Node {
private char val;
private Node[] children;
private boolean isLast;
public Node(char val) {
this.val = val;
children = new Node[26];
isLast = false;
}
}
}
}