Skip to content

Commit 0ac9b42

Browse files
committed
implement trie prefix tree solution
1 parent aac2106 commit 0ac9b42

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
class TrieNode {
2+
TrieNode[] children = new TrieNode[26];
3+
boolean isEnd;
4+
}
5+
6+
class Trie {
7+
8+
private TrieNode root;
9+
10+
public Trie() {
11+
root = new TrieNode();
12+
}
13+
14+
public void insert(String word) {
15+
TrieNode node = root;
16+
for (char c : word.toCharArray()) {
17+
int idx = c - 'a';
18+
if(node.children[idx] == null) {
19+
node.children[idx] = new TrieNode();
20+
}
21+
node = node.children[idx];
22+
}
23+
node.isEnd = true;
24+
}
25+
26+
public boolean search(String word) {
27+
TrieNode node = root;
28+
for(char c : word.toCharArray()) {
29+
int idx = c - 'a';
30+
if(node.children[idx] == null) return false;
31+
node = node.children[idx];
32+
}
33+
34+
return node.isEnd;
35+
}
36+
37+
public boolean startsWith(String prefix) {
38+
TrieNode node = root;
39+
for(char c : prefix.toCharArray()) {
40+
int idx = c - 'a';
41+
if(node.children[idx] == null) return false;
42+
node = node.children[idx];
43+
}
44+
return true;
45+
}
46+
}
47+
48+
/**
49+
* Your Trie object will be instantiated and called as such:
50+
* Trie obj = new Trie();
51+
* obj.insert(word);
52+
* boolean param_2 = obj.search(word);
53+
* boolean param_3 = obj.startsWith(prefix);
54+
*/

0 commit comments

Comments
 (0)