forked from mdabarik/blind-75-leetcode-questions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
71--implement-trie-or-prefix-tree.java
55 lines (48 loc) · 1.43 KB
/
71--implement-trie-or-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
class Trie {
class Node {
HashMap<Character, Node> child = new HashMap<>();
boolean isEnd = false;
}
Node root;
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.child.containsKey(ch)) {
curr.child.put(ch, new Node());
}
curr = curr.child.get(ch);
}
curr.isEnd = true;
} // TC: O(n), SC: O(n)
public boolean search(String word) {
Node curr = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (!curr.child.containsKey(ch))
return false;
curr = curr.child.get(ch);
}
return curr.isEnd;
} // TC: O(n), SC: O(1)
public boolean startsWith(String prefix) {
Node curr = root;
for (int i = 0; i < prefix.length(); i++) {
char ch = prefix.charAt(i);
if (!curr.child.containsKey(ch))
return false;
curr = curr.child.get(ch);
}
return true;
} // TC: O(n), SC: O(1)
}
/**
* 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);
*/