-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trie.java
60 lines (51 loc) · 1.98 KB
/
Trie.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
import java.util.*;
class TrieNode {
Map<Character, TrieNode> children = new HashMap<>();
boolean isEndOfWord = false; // Marks the end of a word
}
class Trie {
private TrieNode root; // Root of the Trie
public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("apple");
System.out.println(trie.search("apple")); // true
System.out.println(trie.search("app")); // false
System.out.println(trie.startsWith("app")); // true
trie.insert("app");
System.out.println(trie.search("app")); // true
}
public Trie() {
root = new TrieNode(); // Initialize the root node
}
// Insert a word into the Trie
public void insert(String word) {
TrieNode current = root;
for (char ch : word.toCharArray()) {
current.children.putIfAbsent(ch, new TrieNode()); // Add child node if absent
current = current.children.get(ch); // Move to the child node
}
current.isEndOfWord = true; // Mark the end of the word
}
// Search for a word in the Trie
public boolean search(String word) {
TrieNode current = root;
for (char ch : word.toCharArray()) {
if (!current.children.containsKey(ch)) {
return false; // If character not found, word doesn't exist
}
current = current.children.get(ch); // Move to the child node
}
return current.isEndOfWord; // Check if it's the end of a valid word
}
// Check if any word starts with a given prefix
public boolean startsWith(String prefix) {
TrieNode current = root;
for (char ch : prefix.toCharArray()) {
if (!current.children.containsKey(ch)) {
return false; // If character not found, prefix doesn't exist
}
current = current.children.get(ch); // Move to the child node
}
return true; // If all characters found, return true
}
}