-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trie.java
42 lines (36 loc) · 1.11 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
class Trie {
TrieNode head;
Set<String> set;
public Trie() {
head = new TrieNode();
set = new HashSet<>();
}
public void insert(String word) {
TrieNode temp = head;
for (int i = 0; i < word.length(); i++) {
int c = word.charAt(i) - 'a';
if (temp.children[c] == null) {
temp.children[c] = new TrieNode();
}
temp = temp.children[c];
}
set.add(word);
}
public boolean search(String word) {
return set.contains(word);
}
public boolean startsWith(String prefix) {
TrieNode temp = head;
for (int i = 0; i < prefix.length(); i++) {
if (temp.children[prefix.charAt(i) - 'a'] == null) return false;
else temp = temp.children[prefix.charAt(i) - 'a'];
}
return true;
}
static class TrieNode {
TrieNode[] children;
public TrieNode() {
this.children = new TrieNode[26];
}
}
}