forked from dimpeshpanwar/Java-Advance-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.java
More file actions
63 lines (55 loc) · 1.72 KB
/
Trie.java
File metadata and controls
63 lines (55 loc) · 1.72 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
/**
* Trie Data Structure Implementation
* ----------------------------------
* Supports insertion and prefix search.
*/
class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isEndOfWord;
}
public class TrieImplementation {
private TrieNode root;
public TrieImplementation() {
root = new TrieNode();
}
// Insert a word into the Trie
public void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int idx = c - 'a';
if (node.children[idx] == null)
node.children[idx] = new TrieNode();
node = node.children[idx];
}
node.isEndOfWord = true;
}
// Search for a full word
public boolean search(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int idx = c - 'a';
if (node.children[idx] == null) return false;
node = node.children[idx];
}
return node.isEndOfWord;
}
// Check if any word starts with given prefix
public boolean startsWith(String prefix) {
TrieNode node = root;
for (char c : prefix.toCharArray()) {
int idx = c - 'a';
if (node.children[idx] == null) return false;
node = node.children[idx];
}
return true;
}
public static void main(String[] args) {
TrieImplementation trie = new TrieImplementation();
trie.insert("apple");
trie.insert("app");
trie.insert("bat");
System.out.println(trie.search("apple")); // true
System.out.println(trie.search("appl")); // false
System.out.println(trie.startsWith("app")); // true
}
}