-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathTrie.java
More file actions
51 lines (44 loc) · 1.17 KB
/
Trie.java
File metadata and controls
51 lines (44 loc) · 1.17 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
class Trie {
class TrieNode {
public TrieNode[] next;
public boolean isWord;
public TrieNode() {
this.next = new TrieNode[26];
this.isWord = false;
}
}
private TrieNode root;
public Trie() {
this.root = new TrieNode();
}
public void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (node.next[c - 'a'] == null) {
node.next[c - 'a'] = new TrieNode();
}
node = node.next[c - 'a'];
}
node.isWord = true;
}
public boolean search(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (node.next[c - 'a'] == null) {
return false;
}
node = node.next[c - 'a'];
}
return node.isWord;
}
public boolean startsWith(String prefix) {
TrieNode node = root;
for (char c : prefix.toCharArray()) {
if (node.next[c - 'a'] == null) {
return false;
}
node = node.next[c - 'a'];
}
return true;
}
}