-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathTrie.java
More file actions
55 lines (49 loc) · 1.39 KB
/
Trie.java
File metadata and controls
55 lines (49 loc) · 1.39 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
package datastructure.tree.leetcode;
/**
* @author roseduan
* @time 2020/10/25 11:11 上午
* @description 实现一个字典树
*/
public class Trie {
private static final int SIZE = 26;
private boolean end;
private final Trie[] children;
/** Initialize your data structure here. */
public Trie() {
this.end = false;
this.children = new Trie[SIZE];
}
/** Inserts a word into the trie. */
public void insert(String word) {
Trie p = this;
for (char c : word.toCharArray()) {
if (p.children[c - 'a'] == null) {
p.children[c - 'a'] = new Trie();
}
p = p.children[c - 'a'];
}
p.end = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
Trie p = this;
for (char c : word.toCharArray()) {
if (p.children[c - 'a'] == null) {
return false;
}
p = p.children[c - 'a'];
}
return p.end;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Trie p = this;
for (char c : prefix.toCharArray()) {
if (p.children[c - 'a'] == null) {
return false;
}
p = p.children[c - 'a'];
}
return true;
}
}