字典树也叫前缀树用法

字典树

Trie树叫字典树也叫前缀树是一种多叉树形结构,是哈希树的变种。

Tire树典型应用于快速体检索,统计,排列和保存大量的字符串。其优点是最大限度减少无谓的字符串比较,查询效率比较高。

Tire树的核心思想是空间换时间,利用字符串的公共前缀和来降低查询时间的开销提高效率。

Tire树的三个基本性质:

根节点不包含字符,除根节点外每一个节点都只包含一个字符。

从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。

每个节点的所有子节点包含的字符都不相同。

有点不好理解就想,一棵树开了26个枝丫,有的有果子,有的没有,每个枝丫上还有26个小枝以此类推。

可以把Trie树看成一个最多26叉树,每个节点的子节点可以最多有有26个。

public class Trie {
    private Trie[] children;
    private boolean isEnd;

    public Trie() {
        children = new Trie[26];//表示26个字母子节点
        isEnd = false;
    }

    public void insert(String word) {
        Trie node = this;//指向当前的根节点
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                node.children[index] = new Trie();//插入这个字母
            }
            node = node.children[index];//指向对应的子节点
        }
        node.isEnd = true;//记录单词结束位置

    }
//查询单词是否在Trie树中
    public boolean search(String word) {
        Trie node = searchPrefix(word);
        return node != null && node.isEnd;

    }
//查询单词的前缀prefix是否在Trie树中。
    public boolean startsWith(String prefix) {
        return searchPrefix(prefix) != null;
    }
//查询单词前缀和是否在Trie树中。
    private Trie searchPrefix(String prefix) {
        Trie node = this;
        for (int i = 0; i < prefix.length(); i++) {
            char ch = prefix.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                return null;
            }
            node = node.children[index];
        }
        return node;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值