字典树(前缀树)

1.什么是前缀树

  • Trie树,即字典树,又称单词查找树或键树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大限度地减少无谓的字符串比较。

  • Trie的核心思想是空间换时间。利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。

2.性质

  • 1.根节点不包含字符,除根节点外每一个节点都只包含一个字符。
  • 2.从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
  • 3.每个节点的所有子节点包含的字符都不相同。

3.代码实现

class Trie {
    private Trie[] children;//使用数组保存子节点
    private boolean isEnd;// 标记是否到达结尾
    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }
    
    //插入方法
    public void insert(String word) {
        Trie node = this;//根节点
        for(int i=0;i<word.length();++i){
            char c = word.charAt(i);
            int index = c-'a';
            //如果该分支不存在,进行创建
            if(node.children[index] == null){
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }
    
    //查找方法
    public boolean search(String word) {
        Trie node = searchPrefix(word);
        return node != null && node.isEnd;
    }
    
    //判断之前插入的字符串是否有这个前缀
    public boolean startsWith(String prefix) {
        return searchPrefix(prefix) != null;
    }
	
	//查找前缀
    private Trie searchPrefix(String prefix){
        Trie node = this;
        for(int i=0;i<prefix.length();++i){
            char c = prefix.charAt(i);
            int index = c-'a';
            if(node.children[index] == null){
                return null;
            }
            node = node.children[index];
        }
        return node;
    }
}
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 12
    评论
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Listen·Rain

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值