字典树基本实现及特性

字典树(Trie)是一种用于高效字符串查询的树形结构,通过利用字符串公共前缀减少比较次数。它不存储完整单词,但路径上的字符组合代表字符串。在Java中,实现字典树涉及节点定义、方法设置以及插入和查找操作。插入和查找的时间复杂度均为O(m),空间复杂度分别为O(m)和O(1)。

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

字典树 Trie

又称单词查找树或者键树,是一种树形结构。典型应用是用于统计和排序大量的字符串(不仅限于字符串),经常被搜索系统用于文本词频统计
它的优点是:最大限度的减少无谓的字符串比较,查询效率比哈希表高。

基本性质

  • 结点本身不存完整单词
  • 从根结点到某一结点,路径上经过的字符连接起来,为该结点所对应的字符串
  • 每个结点所有的子结点路劲代表的字符都不同

核心思想

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

字典树的Java实现

首先对字典树结点进行定义和方法,这里只是有26个小写字母的范围
isEnd()方法,用来判断子节点的这个是否为键 或者是字符串的前缀

class TreeNode {
    private TreeNode[] links;
    private final int R = 26;
    private boolean isEnd;

    /** Initialize your data structure here. */
    public TreeNode() {
        links = new TreeNode[R];
    }
    public boolean containsKey (char ch) {
        return links[ch - 'a'] != null;
    }
    public TreeNode get (char ch) {
        return links[ch - 'a'];
    }
    public void put (char ch, TreeNode node) {
        links[ch - 'a'] = node;
    }
    public boolean isEnd() {
        return isEnd;
    }
    public void setEnd() {
        isEnd = true;
    }
}

字典树的实现

class Trie {
    private TreeNode root;

    public Trie() {
        root = new TreeNode();
    }
    /** Inserts a word into the trie. */
    public void insert(String word) { //插入键
        TreeNode node = root;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            if (!node.containsKey(ch)) {
                node.put(ch, new TreeNode());
            }
            node = node.get(ch);
        }
        node.setEnd();
    }
    
    /** Returns if the word is in the trie. */
    public TreeNode searchStr(String word) { //查找字符串
        TreeNode node = root;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            if (node.containsKey(ch)) {
                node = node.get(ch);
            } else {
                return null;
            }
        }
        return node;
    }
    public boolean search (String word) { //查找键
        TreeNode node = searchStr(word);
        return node != null && node.isEnd();
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) { //查找前缀
        TreeNode node = searchStr(prefix);
        return node != null;
    }
}

复杂度分析

插入操作
时间复杂度:O(m),其中 m 为键长。在算法的迭代中,我们要么检查要么创建一个节点,直到到达键尾。只需要 mm次操作。

空间复杂度:O(m)。最坏的情况下,新插入的键和 Trie 树中已有的键没有公共前缀。此时需要添加 m个结点,使用 O(m)空间。
查找操作
时间复杂度 : O(m)。算法的每一步均搜索下一个键字符。最坏的情况下需要 m次操作。
空间复杂度 : O(1)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值