forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImplement Trie (Prefix Tree).java
44 lines (40 loc) · 1.04 KB
/
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
// Runtime: 67 ms (Top 53.89%) | Memory: 70 MB (Top 22.15%)
class Trie {
private class Node{
char character;
Node[] sub;
Node(char c){
this.character = c;
sub = new Node[26];
}
}
Node root;
HashMap<String, Boolean> map;
public Trie() {
root = new Node('\0');
map = new HashMap<>();
}
public void insert(String word) {
Node temp = root;
for(char c : word.toCharArray()){
int index = c-'a';
if(temp.sub[index] == null)
temp.sub[index] = new Node(c);
temp = temp.sub[index];
}
map.put(word, true);
}
public boolean search(String word) {
return map.containsKey(word);
}
public boolean startsWith(String prefix) {
Node temp = root;
for(char c : prefix.toCharArray()){
int index = c-'a';
if(temp.sub[index] == null)
return false;
temp = temp.sub[index];
}
return true;
}
}