package Tree.TrieTree;
public class TrieNode {
public static class trieNode {
public int pass;//表示当前节点一共经过了多少次
public int end;//表示有多少字符串是以该字符为结尾
public trieNode[] nexts;//表示当前节点的下一个节点
public trieNode() {
pass = 0;
end = 0;
//nexts[0] == null 没有走向'a'的路
//nexts[0] != null 由走向'a'的路
//...
//nexts[25] != null
nexts = new trieNode[26];// 有走向'z'的路
}
}
public static class Trie {
private trieNode root;
public Trie() {
root = new trieNode();
}
public void insert(String word) {
trieNode node = root; //前缀树的节点从根节点开始
if (word == null) { //如果字符串为空
node.pass++;
node.end++;
return;
}
char[] chs = word.toCharArray(); //先将字符串转化为字符数组,方便处理
node.pass++; //首先根节点的经过次数++
int index = 0; //标记当前字符应该在什么位置
for (int i = 0; i < chs.length; i++) {
index = chs[i] - 'a'; //计算当前字符的下标
if (node.nexts[index] == null) { //如果节点不存在就申请节点
node.nexts[index] = new trieNode();
}
node = node.nexts[index];
node.pass++; //该节点的经过次数++
}
node.end++; //当字符串处理完毕之后,最后一个处理的字符就是字符串的结尾,所以处理完以后就end++
}
//word这个单词之前加入过几次
public int search(String word) {
if(word == null) {
return 0;
}
char[] chs = word.toCharArray();
trieNode node = root;
int index = 0;
for(int i = 0;i < chs.length;i++) {
index = chs[i] - 'a'; //找到对应字符的下标
if(node.nexts[index] == null) { //如果找到中间对应的节点还没有建出来就说明该字符串根本没有添加过
return 0;
}
node = node.nexts[index]; //如果该前缀树上有该字符的节点就继续往下走,直到字符串结束
}
//由于字符串每天加一次就会将其路径上的最后一个字符的end++,所以字符串添加过的次数就是对应路径最后一个字符的end值
return node.end;
}
//删除字符串
public void delete(String word) {
if(search(word) != 0) { //如果该字符串从来没有添加过就没有必要删除
char[] chs = word.toCharArray();
trieNode node = root;
node.pass--; //先对路径上的字符经过次数--
int index = 0;
for(int i = 0;i < chs.length;i++) {
index = chs[i] - 'a';
if(--node.nexts[index].pass == 0) { //如果字符串出现的次数为0就将内存释放掉
node.nexts[index] = null;
return;
}
//否则就是字符数组继续向下走
node = node.nexts[index];
}
node.end--; //当字符数组走完之后就对其end--
}
}
}
}
Java实现前缀树(字典树)
最新推荐文章于 2024-07-10 12:15:00 发布