Trie 前缀树 字典树 简介+实现

2023-10-27

简介

在这里插入图片描述
最上面的是根结点, 这棵树中存的单词是apple, app, all, bat, 如果IsWord为True, 就说明从根节点连到这个结点的字母组成的是一个单词

使用前缀树查询的时候时间复杂度只和单词的长度相关

实现

import java.util.TreeMap;

/**
 * 存储只包含26个字母的单词
 */
public class Trie {

    private class Node{
        public boolean isWord;  // 是否是一个单词
        public TreeMap<Character, Node> next;  // 一个字母到其他字母结点的映射

        public Node(boolean isWord){
            this.isWord = isWord;
            next = new TreeMap<>();
        }

        public Node(){
            this(false);
        }
    }

    private Node root;
    private int size;

    public Trie(){
        root = new Node();
        size = 0;
    }

    public int getSize(){
        return size;
    }

    /**
     * 向Trie中添加一个新的单词word
     * @param word
     */
    public void add(String word){
        Node cur = root;
        for(int i=0; i<word.length(); i++){
            char c = word.charAt(i);
            // 当前结点不包含到word[i]的结点
            if(cur.next.get(c) == null){
                cur.next.put(c, new Node());  // 新建一个映射
            }
            cur = cur.next.get(c);
        }
        // 如果之前不是个词
        if(cur.isWord == false){
            cur.isWord = true;
            size++;
        }
    }

    /**
     * 查询到单词是否在Trie中
     * @param word
     * @return
     */
    public boolean contains(String word){
        Node cur = root;
        for(int i=0; i<word.length(); i++){
            char c = word.charAt(i);
            if(cur.next.get(c) == null){
                return false;
            }
            cur = cur.next.get(c);
        }
        return cur.isWord;
    }

    /**
     * 可以用 "." 去匹配任意一个字母
     * @param word
     * @return
     */
    public boolean search(String word){
        return search(root, word, 0);
//        return search(root, word);
    }

    /**
     *
     * @param node
     * @param word
     * @param index 表示从word的索引index开始匹配
     * @return
     */
    private boolean search(Node node, String word, int index) {
        // 已经匹配完
        if(index == word.length())
            return node.isWord;

        char c = word.charAt(index);
        if(c != '.'){
            // 如果已经没有下个结点了
            if(node.next.get(c) == null)
                return false;
            return search(node.next.get(c), word, index+1);
        }
        else{
            for(Node nextNode: node.next.values())
                if(search(nextNode, word, index+1))
                    return true;
            return false;  // 遍历完都没有匹配中的
        }
    }

    /**
     *
     * @param node
     * @param word
     * @return
     */
    private boolean search(Node node, String word) {
        if(word.equals("")){
            if(node.isWord){
                return true;
            }
            else{
                return false;
            }
        }

        if(word.charAt(0) == '.'){
            for(Node nextNode: node.next.values()){
                boolean res = search(nextNode, word.substring(1));
                if(res == true){
                    return true;
                }
            }
        }
        else if(node.next.get(word.charAt(0)) != null){
            return search(node.next.get(word.charAt(0)), word.substring(1));
        }
        return false;
    }

    /**
     * 查询是否存在Trie中有单词以prefix为前缀
     * @param prefix
     * @return
     */
    public boolean isPrefix(String prefix){
        Node cur = root;
        for(int i=0; i<prefix.length(); i++){
            char c = prefix.charAt(i);
            if(cur.next.get(c) == null){
                return false;
            }
            cur = cur.next.get(c);
        }
        return true;
    }



    public static void main(String[] args) {
        Trie t = new Trie();
        t.add("bad");
        t.add("pad");
        System.out.println(t.contains("bad"));
        System.out.println(t.isPrefix("ba"));
        System.out.println(t.search("ba."));
        System.out.println(t.search(".ad"));
        System.out.println(t.search(".a."));
        System.out.println(t.search("..."));
        System.out.println(t.search("p.a"));
        System.out.println(t.search("b."));
    }
}

练习

LeetCode 677
思路见注释
假如 insert(“apple”, 3), insert(“all”, 2)

class MapSum {

    private class Node{
        public int value;  // apple的最后一个Node e的value就是3, 前面Node a, p, p, l的value都是0
        public TreeMap<Character, Node> next;  // 如果Node是a, 那next就是Node p, Node l

        // 构造函数
        public Node(int value){
            this.value = value;
            next = new TreeMap<>();
        }

        // 构造函数
        public Node(){
            this(0);
        }
    }

    private Node root;  // 用上面的例子的话, root的next是Node a

    /** Initialize your data structure here. */
    public MapSum() {
        root = new Node();
    }

    public void insert(String key, int val) {
        Node cur = root;
        for(int i=0; i<key.length(); i++){
            char c = key.charAt(i);
            // 如果不存在这个字母的Node, 创建
            if(cur.next.get(c) == null)
                cur.next.put(c, new Node());
            // 移动
            cur = cur.next.get(c);
        }
        cur.value = val;
    }

    public int sum(String prefix) {
        Node cur = root;
        for(int i=0; i<prefix.length(); i++){
            char c = prefix.charAt(i);
            if(cur.next.get(c) == null)
                return 0;
            cur = cur.next.get(c);
        }
        return sum(cur);
    }

    private int sum(Node node){
        // if(node.next.size() == 0)
        //     return node.value;
        // 这个递归结束的语句已包含在下面

        int res = node.value;
        for(Node nextNode: node.next.values()){
            res += sum(nextNode);
        }
        return res;
    }

    public static void main(String[] args) {
        MapSum ms = new MapSum();
        ms.insert("apple", 3);
        ms.insert("app", 8);
        ms.insert("bao", 8);
//        ms.sum("ap");
        System.out.println(ms.sum("ap"));
    }
}

其他

局限性: 占用的空间会更多, 可以使用压缩字典树来解决, 但维护成本又会上去, 有得必有失
在这里插入图片描述
还可以用三分搜索树
在这里插入图片描述在这里插入图片描述
上面这棵树中存了单词dog

后面三张图来源 link

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Trie 前缀树 字典树 简介+实现 的相关文章

随机推荐

  • 写论文和做项目中遇到的问题及其解决办法

    相比Microsoft Office Word 我更推荐用WPS Office Word编写论文 感觉后者用起来更轻松 1 利用Word自带的的标题样式快速给文档设置一到三级标题 2 Word文档中具有编辑器自带标题样式的文字前面都有小黑方
  • 【YOLOv5-6.x】设置可学习权重结合BiFPN(Add操作)

    文章目录 前言 修改yaml文件 以yolov5s为例 只修改一处 将Concat全部换成BiFPN Add 打印模型参数 修改common py 修改yolo py 修改train py 1 向优化器中添加BiFPN的权重参数 2 查看B
  • 疼失鸡鸡,吊唁鸡鸡

    为了忘却的纪念 今天是我痛失鸡鸡的日子 一个好鸡鸡是很难找的 一个集群的鸡鸡跟难找的 为了吊唁我的鸡鸡 我觉得为它写一篇文章
  • Matplot pyplot绘制单图,多子图不同样式详解,这一篇就够了

    Matplot pyplot绘制单图 多子图不同样式详解 这一篇就够了 1 单图单线 2 单图多线不同样式 红色圆圈 蓝色实线 绿色三角等 2 1 4 支持的所有颜色及样式 3 使用关键字字符串绘图 data 可指定依赖值为 numpy r
  • 【BLE】蓝牙抓包器 Ellisys 使用说明

    BLE 蓝牙抓包器 Ellisys 使用说明 常用功能 设备过滤 抓包的类型 添加观察的项目 协议解析 连接过程 Connection Indication LLCP Feature Request Response LLCP Length
  • Java多线程通信-CountDownLatch(闭锁)

    一 CountDownLatch 闭锁 闭锁是一个同步工具类 它可以延迟线程的进度直到其到达终止状态 闭锁的作用相当于一扇门 在到达结束状态之前 这扇门是关闭的 并且不允许任何进程通过 当到达结束状态时 这扇门会打开并允许所有的线程通过 当
  • wangeditor3.0上传本地图片和本地视频至服务器

    1 效果 2 注意 我下载的3 0版本 3 组件 在components文件里创建一个wangEditoe vue文件
  • Java基于opencv实现图像数字识别(一)

    Java基于opencv实现图像数字识别 一 最近分到了一个任务 要做数字识别 我分配到的任务是把数字一个个的分开 当时一脸懵逼 直接百度java如何分割图片中的数字 然后就百度到了用BufferedImage这个类进行操作 尝试着做了一下
  • Vue生命周期和钩子函数详解

    Vue生命周期和钩子函数详解 Vue生命周期介绍 组件每个阶段它的内部构造是不一样的 所以一般特定的钩子做特定的事 比如Ajax获取数据就可以在mounted阶段 从Vue实例被创建开始到该实例最终被销毁的整个过程叫做VUE的生命周期 在这
  • A*算法学习笔记

    1 算法思路 1 Dijkstra算法与A 算法 1 Dijkstra算法 贪心策略 优先队列 集合S 已确定的顶点集合 初始只含源点s 集合T 尚未确定的顶点集合 算法反复从集合T中选择当前到源点s最近的顶点u 将u加入集合S 然后对所有
  • 使用myisamchk命令修复表 只能修复myisam表 速度块

    快速检查 myisamchk im var lib mysql db1 只检查没有正常关闭的表 myisamchk iFm var lib mysql db1 仅显示标的重要信息 myisamchk eis var lib mysql db
  • 【Markdown】Typora配置图片上传

    文章目录 0 前言 1 确定需求 2 开始配置 2 1 软件储备 2 2 插件安装 2 3 gitee配置 3 其他配置 3 1 获取SMMS token 参考链接 0 前言 对于喜欢写Markdown文档的人来说 Typora无疑是一个写
  • 30分钟学会如何使用Shiro

    http www cnblogs com learnhow p 5694876 html 一 架构 要学习如何使用Shiro必须先从它的架构谈起 作为一款安全框架Shiro的设计相当精妙 Shiro的应用不依赖任何容器 它也可以在JavaS
  • 宏定义详细知识点

    一 不带参数的宏定义 1 格式 define 宏名 字符串 例 define a 6 则a是宏名 凡是出现a的地方均用6替换 2 注意 宏替换是一种机械替换 不做语法检查 不是下一个语句 其后不加 define命令出现在函数的外面 有效范围
  • 框架中常见的设计模式有哪些学习总结第一篇

    框架中常见的设计模式有哪些 设计模式的作用 通过设计模式写代码 设计模式可以解耦 解耦只是一种思想 代码开发的时候 把代码分开便于维护和管理 运行的时候再合并起来运行 回顾软件设计原则 开闭原则 对扩展开放 对修改关闭 使用范围特变广 单一
  • c语言之实现fastcgi协议的代码完整实现

    FastCGI协议是在CGI协议的基础上发展出来的 如果想了解CGI协议 可以看我另一篇文章 动态web技术 二 CGI FastCGI程序本身监听某个socket然后等待来自web服务器的连接 而不是像CGI程序是由web服务器 fork
  • Android Studio 快速跳转到XML布局界面

    http www jianshu com p 8ca15b831b31 我们开发Android应用程序时 Activity或者Fragment会有一个相对应的布局 在Eclipse中或者一般的做法 我们会在Java代码中找到对应的代码 然后
  • jquery之ajax——全局事件引用方式以及各个事件(全局/局部)执行顺序

    jquery中各个事件执行顺序如下 1 ajaxStart 全局事件 2 beforeSend 局部事件 3 ajaxSend 全局事件 4 success 局部事件 5 ajaxSuccess 全局事件 6 error 局部事件 7 aj
  • Python画图示例(1) 一维数据集绘图

    Python画图示例 1 一维数据集绘图 Python画图示例 2 二维数据集绘图 Python画图示例 3 其他绘图样式 散点图 直方图等 Python画图示例 4 3D绘图 目录 1 用 Numpy ndarray 作为数据传入 ply
  • Trie 前缀树 字典树 简介+实现

    简介 最上面的是根结点 这棵树中存的单词是apple app all bat 如果IsWord为True 就说明从根节点连到这个结点的字母组成的是一个单词 使用前缀树查询的时候时间复杂度只和单词的长度相关 实现 import java ut