-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.java
More file actions
70 lines (52 loc) · 1.67 KB
/
Copy pathTrie.java
File metadata and controls
70 lines (52 loc) · 1.67 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
package LeetcodePractice;
class Trie {
private TrieNode root;
private static class TrieNode {
TrieNode[] children;
boolean isEndOfWord;
TrieNode() {
children = new TrieNode[26];
isEndOfWord = false;
}
}
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
int index = ch - 'a';
if (node.children[index] == null) {
node.children[index] = new TrieNode();
}
node = node.children[index];
}
node.isEndOfWord = true;
}
public boolean search(String word) {
TrieNode node = searchPrefix(word);
return node != null && node.isEndOfWord;
}
public boolean startsWith(String prefix) {
return searchPrefix(prefix) != null;
}
private TrieNode searchPrefix(String prefix) {
TrieNode node = root;
for (char ch : prefix.toCharArray()) {
int index = ch - 'a';
if (node.children[index] == null)
return null;
node = node.children[index];
}
return node;
}
public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("apple");
System.out.println("search(\"apple\"): " + trie.search("apple"));
System.out.println("search(\"app\"): " + trie.search("app"));
System.out.println("startsWith(\"app\"): " + trie.startsWith("app"));
trie.insert("app");
System.out.println("search(\"app\"): " + trie.search("app"));
}
}