前缀树

博客介绍了前缀树,它又称字典树,是可简化字符串处理的数据结构。还提及实现前缀树的相关内容,包括结点结构、插入和删除字符串操作,以及统计字符串出现次数和以给定字符为前缀的字符串个数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前缀树

前缀树又称字典树,是一种可以简化字符串处理的一种数据结构。

实现一棵前缀树
  • 结点结构:
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值