前缀树
前缀树又称字典树,是一种可以简化字符串处理的一种数据结构。
实现一棵前缀树
- 结点结构:
public class TrieNode{
public int path; // 插入字符串的过程中经过了多少次
public int end; // 有多少个字符串以该字符结尾
public TrieNode[] next;
public TrieNode(){
path = 0;
end = 0;
next = new TrieNode[26]; // 默认全是小写字母
}
}
- 向前缀树中插入字符串
public void insert(String word){
if(word == null){
return;
}
char[] arr = word.toCharArray();
TrieNode node = root;
int index = 0;
for(int i = 0; i < arr.length; i++){
index = arr[i] - 'a';
if(node.next[index] == null){ // 不存在这样的路径建出来
node.next[index] = new TrieNode();
}
node.path++;
node = node.next[index];
}
node.end++;
}
- 在前缀树中删除一个字符串
public void delete(String word){
if(word == null){
return;
}
int index = 0;
TrieNode node = root;
char[] arr = word.toCharArray();
for(int i = 0; i < arr.length; i++){
index = arr[i] - 'a';
if(node.next[index] == null){
return;
}
if(--node.next[index].path == 0){
node.next[index] = null;
return;
}
node = node.next[index];
}
node.end--;
}
- 某个字符串在前缀树中出现了几次
public int search(String word){
if(word == null){
return 0;
}
char[] arr = word.toCharArray();
TrieNode node = root;
int index = 0;
for(int i = 0;i < arr.length; i++){
index = arr[i] - 'a';
if(node.next[index] == null){
return 0;
}
}
return node.end;
}
- 前缀树中以给定字符为前缀的字符串个数
public int prefixNumber(String word){
if(word == null){
return 0;
}
int index = 0;
TrieNode node = root;
char[] arr = word.toCharArray();
for(int i = 0; i < arr.length; i++){
index = arr[i] - 'a';
if(node.next[index] == null){
return 0;
}
node = node.next[index];
}
return node.path;
}