-
Notifications
You must be signed in to change notification settings - Fork 15
/
Problem_1_Implement_Trie_Prefix_Tree.java
48 lines (40 loc) · 1.26 KB
/
Problem_1_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
45
46
47
48
package Trie;
// Problem Statement: Implement Trie (Prefix Tree) (medium)
// LeetCode Question: 208. Implement Trie (Prefix Tree)
public class Problem_1_Implement_Trie_Prefix_Tree {
class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isEnd;
public TrieNode(){};
}
private TrieNode root;
public Problem_1_Implement_Trie_Prefix_Tree(TrieNode root) {
this.root = new TrieNode();
}
public void insert(String word){
TrieNode node = root;
for (char c : word.toCharArray()){
if (node.children[c - 'a'] == null) {
node.children[c - 'a'] = new TrieNode();
}
node = node.children[c - 'a'];
}
node.isEnd = true;
}
public boolean search(String word){
TrieNode node = root;
for (char c : word.toCharArray()){
if (node.children[c - 'a'] == null) return false;
node = node.children[c - 'a'];
}
return node.isEnd;
}
public boolean startsWith(String prefix) {
TrieNode node = root;
for (char c : prefix.toCharArray()){
if (node.children[c - 'a'] == null) return false;
node = node.children[c - 'a'];
}
return true;
}
}