Skip to content

Commit d6c9070

Browse files
authored
Merge pull request neetcode-gh#53 from ArwaNayef/patch-3
Create 208-Implement-Trie(Prefix Tree)
2 parents 1f1b473 + 7830945 commit d6c9070

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 Trie {
2+
Node root;
3+
4+
public Trie() {
5+
root = new Node('\0'); //dummy node
6+
}
7+
8+
public void insert(String word) {
9+
Node curr = root;
10+
for (char x : word.toCharArray()) {
11+
if (curr.children[x - 'a'] == null) {
12+
curr.children[x - 'a'] = new Node(x);
13+
}
14+
curr = curr.children[x - 'a'];
15+
}
16+
curr.isWord = true;
17+
}
18+
19+
public boolean search(String word) {
20+
Node res = getLast(word);
21+
return (res != null && res.isWord);
22+
}
23+
24+
//helper method
25+
public Node getLast(String word) {
26+
Node curr = root;
27+
for (char x : word.toCharArray()) {
28+
if (curr.children[x - 'a'] == null) {
29+
return null;
30+
}
31+
32+
curr = curr.children[x - 'a'];
33+
}
34+
return curr;
35+
}
36+
37+
public boolean startsWith(String prefix) {
38+
Node res = getLast(prefix);
39+
if (res == null) return false;
40+
return true;
41+
}
42+
43+
class Node {
44+
private char value;
45+
private boolean isWord;
46+
private Node[] children;
47+
48+
public Node(char val) {
49+
this.value = val;
50+
this.isWord = false;
51+
this.children = new Node[26];
52+
}
53+
}
54+
}

0 commit comments

Comments
 (0)