前缀树
也叫字典树,也是一种多叉树的结构
节点类型
- path:有多少个单词以它为前缀
- end: 有多少个单词以它结尾
public static class TrieNode {
public int path;//有多少个单词以它为前缀
public int end;//有多少个单词以它结尾
public TrieNode[] map;//多叉结构,这里全是英文小写字母就开辟长度为26的,如果是汉子或者其他字符不定的情况可以使用HashMap代替这个数组结构
public TrieNode() {
path = 0;
end = 0;
map = new TrieNode[26];
}
}
如何生成前缀树
public class TrieTree {
public static class TrieNode {
public int path;
public int end;
public TrieNode[] map;
public TrieNode() {
path = 0;
end = 0;
map = 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[] chs = word.toCharArray();
TrieNode node = root;
int index = 0;
for (int i = 0; i < chs.length; i++) {
index = chs[i] - 'a';//ASCII-'a' a表示为整形的0 存的时候存的整形值
if (node.map[index] == null) {//下面没节点就开辟新节点
node.map[index] = new TrieNode();
}
node = node.map[index];//当前节点下移
node.path++;//经过它的节点数++
}
node.end++;//以它为结束节点的计数++
}
public void delete(String word) {
if (search(word)) {//先查询这个词是否存在,不存在就不用删
char[] chs = word.toCharArray();
TrieNode node = root;
node.path--;//node的头结点先-- 头结点不存在就不需要向下了
int index = 0;
for (int i = 0; i < chs.length; i++) {
index = chs[i] - 'a';
if (node.map[index].path-- == 1) {//path==1说明这已经是最后一个节点了,直接删除就可以
node.map[index] = null;
return;
}
node = node.map[index];//当前节点向下
}
node.end--;//以当前节点为结束的计数--
}
}
public boolean search(String word) {
if (word == null) {
return false;
}
char[] chs = word.toCharArray();
TrieNode node = root;
int index = 0;
for (int i = 0; i < chs.length; i++) {
index = chs[i] - 'a';
if (node.map[index] == null) {
return false;
}
node = node.map[index];
}
return node.end != 0;//存在以最后一个字符结束的分支则前缀树存在
}
public int prefixNumber(String pre) {
if (pre == null) {
return 0;
}
char[] chs = pre.toCharArray();
TrieNode node = root;
int index = 0;
for (int i = 0; i < chs.length; i++) {
index = chs[i] - 'a';
if (node.map[index] == null) {
return 0;
}
node = node.map[index];
}
return node.path;//当前节点的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"));
}
}