-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathTrie.java
64 lines (52 loc) · 1.37 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package leetcode.datastructure;
/**
* 前缀树 单词查找树 Trie树
* 它没有保存任何字符,只是记录了字符引用和单词结尾的标志位(isEnd)
*
* @author FangYuan
* @since 2024-02-11 16:40:00
*/
public class Trie {
static class Node {
boolean isEnd;
Node[] next;
public Node() {
isEnd = false;
next = new Node[26];
}
}
private Node root;
public Trie() {
root = new Node();
}
public void insert(String word) {
Node node = root;
char[] charArray = word.toCharArray();
for (char c : charArray) {
if (node.next[c - 'a'] == null) {
node.next[c - 'a'] = new Node();
}
node = node.next[c - 'a'];
}
node.isEnd = true;
}
public boolean search(String word) {
Node node = doSearch(word);
return node != null && node.isEnd;
}
private Node doSearch(String word) {
Node node = root;
char[] charArray = word.toCharArray();
for (char c : charArray) {
if (node.next[c - 'a'] == null) {
return null;
}
node = node.next[c - 'a'];
}
return node;
}
public boolean startsWith(String prefix) {
Node node = doSearch(prefix);
return node != null;
}
}