字典树(Trie)

字典树是一种数据结构,用于高效存储和查询字符串。它通过利用字符串的公共前缀减少查询时间,适用于动态查询。与哈希表相比,字典树在查询整个单词时效率稍低,但能处理部分匹配。文章提供了字典树的Java实现,包括插入、查找和搜索前缀功能。

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

字典树Trie),也叫前缀树,是一个比较简单的数据结构,用来存储和查询字符串。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较。例如,hellohihahahaga这几个单词可以用以下方式存储:

在这里插入图片描述

基本思想

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

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

字典树查询和哈希查询之间的区别:

  1. 字典树的查询时间复杂度是 O ( L ) O(L) O(L),L是字符串的长度。哈希查询的时间复杂度为 O ( 1 ) O(1) O(1)。因此,在查询一整个单词的时候,哈希查询比较快。
  2. 哈希查询不支持动态查询,即查看单词时不能查找单词的一部分。

代码实现

其核心代码为:

public class Template {

    class TreeNode {
        int count = 0;
        int prefix = 0;
        TreeNode[] chd = new TreeNode[26];
    }

    /**
     * 插入单词
     *
     * @param node
     * @param word
     */
    public void insert(TreeNode node, String word) {
        if (word == null || word.length() == 0) return;
        int len = word.length();
        for (int i = 0; i < len; i++) {
            int pos = word.charAt(i) - 'a';
            if (node.chd[pos] == null) node.chd[pos] = new TreeNode();
            node = node.chd[pos];
            node.prefix++;
        }
        node.count++;
    }

    /**
     * 查找对应的结点
     *
     * @param node
     * @param word
     * @return
     */
    public TreeNode searchNode(TreeNode node, String word) {
        if (word == null || word.length() == 0) return null;
        int len = word.length();
        for (int i = 0; i < len; i++) {
            int pos = word.charAt(i) - 'a';
            if (node.chd[pos] == null) return null;
            node = node.chd[pos];
        }
        return node;
    }

    /**
     * 查找单词
     *
     * @param node
     * @param word
     * @return
     */
    public int searchWord(TreeNode node, String word) {
        TreeNode target = searchNode(node, word);
        if (target == null) return 0;
        return target.count;
    }

    /**
     * 查看前缀
     *
     * @param node
     * @param word
     * @return
     */
    public int searchPrefix(TreeNode node, String word) {
        TreeNode target = searchNode(node, word);
        if (target == null) return 0;
        return target.prefix;
    }

    public static void main(String[] args) {
        Template temp = new Template();
        TreeNode node = temp.new TreeNode();
        temp.insert(node, "hello");
        temp.insert(node, "hi");
        temp.insert(node, "haha");
        temp.insert(node, "ha");
        System.out.println(temp.searchPrefix(node, "h"));
        System.out.println(temp.searchWord(node, "ha"));
    }
}

参考文献:

  1. 数据结构与算法:字典树(前缀树)
  2. 算法学习笔记(43): 字典树
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值