-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCode_01_TrieTree.java
More file actions
115 lines (104 loc) · 3.28 KB
/
Code_01_TrieTree.java
File metadata and controls
115 lines (104 loc) · 3.28 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package algorithm.basic07;
/**
* @Created by mood321
* @Date 2019/11/8 0008
* @Description TODO
*/
public class Code_01_TrieTree {
public static class TrieNode {
public int path;// 拥有节点个数
public int end;//尾节点个数
public TrieNode[] nexts;// 子节点 因为字符字母 可以用数组 也可以用map
public TrieNode() {
nexts = new TrieNode[26];
}
}
public static class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
// 添加
public void insert(String word) {
if (word == null)
return;
char[] chars = word.toCharArray();
TrieNode node = root;
for (int i = 0; i < chars.length; i++) {
int i1 = chars[i] - 'a';
if (node.nexts[i1] == null)
node.nexts[i1] = new TrieNode();
node = node.nexts[i1];
node.path++;
}
node.end++;
}
// 查找
public int search(String word) {
if(word==null)
return 0;
char[] chars = word.toCharArray();
int index=0;
TrieNode node = this.root;
for (int i = 0; i < chars.length; i++) {
index=chars[i]-'a';
if(node.nexts[index]==null)
return 0;
node=node.nexts[index];
}
return node.end;
}
public void delete(String word) {
if(search(word)>0){
char[] chars = word.toCharArray();
TrieNode node = this.root;
int index=0;
for (int i = 0; i < chars.length; i++) {
index=chars[i]-'a';
if(0==node.nexts[index].path) {
node.nexts[index] = null;
return;
}
node=node.nexts[index];
}
node.end--;
}
}
public int prefixNumber(String pre) {
if(pre==null)
return 0;
char[] chars = pre.toCharArray();
TrieNode node = this.root;
int index=0;
for (int i = 0; i < chars.length; i++) {
index = chars[i] - 'a';
if (node.nexts[index]==null) {
return 0;
}
node=node.nexts[index];
}
return node.path;
}
}
public static void main(String[] args) {
Trie trie = new Trie();
System.out.println(trie.search("zuo"));
trie.insert("zuo");
System.out.println(trie.search("zuo"));
trie.delete("zuo");
System.out.println(trie.search("zuo"));
trie.insert("zuo");
trie.insert("zuo");
trie.delete("zuo");
System.out.println(trie.search("zuo"));
trie.delete("zuo");
System.out.println(trie.search("zuo"));
trie.insert("zuoa");
trie.insert("zuoac");
trie.insert("zuoab");
trie.insert("zuoad");
trie.delete("zuoa");
System.out.println(trie.search("zuoa"));
System.out.println(trie.prefixNumber("zuo"));
}
}