forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImplementTrie.java
64 lines (56 loc) · 1.6 KB
/
ImplementTrie.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
58
59
60
61
62
63
64
class Trie {
private TrieNode root;
private class TrieNode{
private TrieNode[] children = null;
private boolean isWord;
public TrieNode(){
children = new TrieNode[26];
}
}
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode it = root;
for(char c : word.toCharArray()) {
int indexInTrieNode = c - 'a';
if(it.children[indexInTrieNode] ==null){
it.children[indexInTrieNode] = new TrieNode();
}
it = it.children[indexInTrieNode];
}
it.isWord = true;
}
public boolean search(String word) {
TrieNode it = root;
for(char c : word.toCharArray()){
int indexInTrieNode = c - 'a';
if(it.children[indexInTrieNode] == null){
// no node was found
return false;
} else{
it = it.children[indexInTrieNode];
}
}
return it.isWord;
}
public boolean startsWith(String prefix) {
TrieNode it = root;
for(char c : prefix.toCharArray()){
int indexInTrieNode = c - 'a';
if(it.children[indexInTrieNode] == null){
return false;
} else{
it = it.children[indexInTrieNode];
}
}
return true;
}
}
/**
* 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);
*/