-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay24.java
More file actions
56 lines (54 loc) · 1.65 KB
/
Day24.java
File metadata and controls
56 lines (54 loc) · 1.65 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
public class Day24 {
private TrieNode root;
public Day24() {
root = new TrieNode('\0');
}
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;
}
public boolean search(String word) {
TrieNode node = searchNode(word);
return node != null && node.isEnd;
}
public boolean startsWith(String prefix) {
return searchNode(prefix) != null;
}
private TrieNode searchNode(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null) {
return null;
}
node = node.children[index];
}
return node;
}
public static void main(String[] args) {
Day24 trie = new Day24();
trie.insert("apple");
trie.insert("app");
trie.insert("apricot");
System.out.println("Search for 'app': " + trie.search("app"));
System.out.println("Search for 'orange': " + trie.search("orange"));
System.out.println("Starts with 'ap': " + trie.startsWith("ap"));
}
}
class TrieNode {
char value;
boolean isEnd;
TrieNode[] children;
TrieNode(char value) {
this.value = value;
this.isEnd = false;
this.children = new TrieNode[26];
}
}