package com.zhang.reflection.面试.算法模版.前缀树;
public class 前缀树 {
private TreeNode root;
static class TreeNode {
public int pass;//经过此结点的边的数量
public int end;//以此边为结束
public TreeNode[] nexts;
public TreeNode() {
this.pass = 0;
this.end = 0;
this.nexts = new TreeNode[26];
}
}
public void insert(String word) {
if (word == null) {
return;
}
char[] chars = word.toCharArray();
TreeNode node = root;
int index = 0;
for (int i = 0; i < chars.length; i++) {
index = chars[i] - 'a';
if (node.nexts[index] == null) {
node.nexts[index] = new TreeNode();
}
node = node.nexts[index];
node.pass++;
}
node.end++;
}
//完整前缀
public int search(String word) {
if (word == null) {
return 0;
}
char[] chars = word.toCharArray();
TreeNode node = 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.end;
}
public void delete(String word) {
if (word == null || search(word) == 0) {
return;
}
char[] chars = word.toCharArray();
TreeNode node = root;
int index = 0;
for (int i = 0; i < chars.length; i++) {
index = chars[i] - 'a';
if (--node.nexts[index].pass == 0) {
node.nexts[index] = null;
return;
}
node = node.nexts[index];
}
node.end--;
}
}