-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathTrie.java
More file actions
76 lines (63 loc) · 1.75 KB
/
Trie.java
File metadata and controls
76 lines (63 loc) · 1.75 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
// Implementation of Trie data structure in java.
/*
* Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_0 = obj.search(word);
* boolean param_1 = obj.startsWith(word);
*/
// Create Trie node
class TrieNode {
public char val;
public boolean isEnd;
public TrieNode[] children;
// Constructor
public TrieNode(char val) {
this.val = val;
this.isEnd = false;
this.children = new TrieNode[26];
}
}
class Trie {
private TrieNode root;
// Create root node
public Trie() {
root = new TrieNode(' ');
}
// Insert a word into the Trie
public void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null) {
node.children[index] = new TrieNode(c);
}
node = node.children[index];
}
node.isEnd = true; // Mark the end of a word
}
// Search for a word in the Trie
public boolean search(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null) {
return false;
}
node = node.children[index];
}
return node.isEnd;
}
// Check if a word in Trie starts with prefix
public boolean startsWith(String prefix) {
TrieNode node = root;
for (char c : prefix.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null) {
return false;
}
node = node.children[index];
}
return true;
}
}