数据结构与算法-Trie树添加与搜索

trie树的使用场景

我们若需要制作一个通讯录的软件,使用常规树结构查询的复杂度为O(logn),但trie树的复杂度确与数据多少无关,与单词长度有关,这就大大缩减的查询的时间复杂度。

trie树的基本实现

基础结构

package com.study.trieDemo;

import java.util.TreeMap;

/**
 * Created by Zsy on 2020/8/21.
 */
public class Trie {
    private class Node {
        private boolean isWord;
        private TreeMap<Character, Node> next;

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

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


    private Node root;
    private int size;


    public int getSize() {
        return size;
    }


 
}

添加

   /**
     * 向tire中添加一个单词
     * @param word
     */
    public void add(String word) {
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (cur.next.get(c) == null)
                cur.next.put(c, new Node());
            cur = cur.next.get(c);
        }

        if (!cur.isWord) {
            cur.isWord = true;
            size++;
        }
    }

搜索单词

  /**
     * 查找单词word是否在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;
    }

leetcode中关于trie的题目

208. 实现 Trie (前缀树)

208. 实现 Trie (前缀树)

实现

package com.study.leetcode;

import java.util.TreeMap;

/**
 * Created by Zsy on 2020/8/21.
 */
public class Trie_208 {


    private Node root;

    private class Node {
        private boolean isWord;
        private TreeMap<Character, Node> next;

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

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

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

    /**
     * Inserts a word into the trie.
     */
    public void insert(String word) {
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (cur.next.get(c) == null)
                cur.next.put(c, new Node());
            cur = cur.next.get(c);
        }
        cur.isWord = true;
    }

    /**
     * Returns if the word is in the trie.
     */
    public boolean search(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;
    }

    /**
     * Returns if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(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;
    }
}

211. 添加与搜索单词 - 数据结构设计

题目链接

211. 添加与搜索单词 - 数据结构设计

实现

package com.study.leetcode;

import java.util.TreeMap;

/**
 * Created by Zsy on 2020/8/21.
 */
public class WordDictionary_211 {

    private Node root;

    private class Node {
        private boolean isWord;
        private TreeMap<Character, Node> next;

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

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


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

    /**
     * Adds a word into the data structure.
     */
    public void addWord(String word) {
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (cur.next.get(c) == null)
                cur.next.put(c, new Node());
            cur = cur.next.get(c);
        }
        cur.isWord = true;
    }

    /**
     * Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
     */
  /**
     * 使用match进行递归查询
     * @param word
     * @return
     */
    public boolean search(String word) {
        return match(root, word, 0);
    }

    private boolean match(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 match(node.next.get(c), word, index + 1);
        } else {
            for (char nextChar : node.next.keySet())
                if (match(node.next.get(nextChar), word, index + 1))
                    return true;
            return false;

        }
    }

}

677. 键值映射

题目链接

677. 键值映射

题解

package com.study.leetcode;

import java.util.TreeMap;

/**
 * Created by Zsy on 2020/8/21.
 */
public class MapSum_677 {
    private class Node {

        public int value;
        public TreeMap<Character, Node> next;

        public Node(int value) {
            this.value = value;
            next = new TreeMap<Character, Node>();
        }

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

    private Node root;

    /**
     * Initialize your data structure here.
     */
    public MapSum_677() {

        root = new Node();
    }

    /**
     * 非递归法插入节点,通过查询next中是否存在对应key的节点,进行相应插入操作
     * @param key
     * @param val
     */
    public void insert(String key, int val) {

        Node cur = root;
        for (int i = 0; i < key.length(); i++) {
            char c = key.charAt(i);
            if (cur.next.get(c) == null)
                cur.next.put(c, new Node());
            cur = cur.next.get(c);
        }
        cur.value = val;
    }


    /**
     * 找到匹配节点的指针,将地址传给sum进行递归计算
     * @param prefix
     * @return
     */
    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==null) return 0;

        int value = node.value;
        for (char c : node.next.keySet()) {
            value+=sum(node.next.get(c));
        }
        return value;
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/883244.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

VSCode编程配置再次总结

VScode 中C++编程再次总结 0.简介 1.配置总结 1.1 launch jsion文件 launch.json文件主要用于运行和调试的配置,具有程序启动调试功能。launch.json文件会启用tasks.json的任务,并能实现调试功能。 左侧任务栏的第四个选项运行和调试,点击创建launch.json {"conf…

String类常用的方法

源代码&#xff1a; 输出结果&#xff1a;

卡码网KamaCoder 108. 冗余连接

题目来源&#xff1a;108. 冗余连接 C题解&#xff08;思路来源代码随想录&#xff09;&#xff1a;并查集。因为原来是树&#xff0c;所以加入边之前肯定不是一个根&#xff0c;如果是一个根&#xff0c;再加一条边&#xff0c;肯定成环。所以只要找到根一致的两个点组成的边即…

前端工程化4:从0到1构建完整的前端监控平台

前言 一套完整的前端监控系统的主要部分&#xff1a; 数据上报方式数据上送时机性能数据采集错误数据采集用户行为采集定制化指标监控sdk 监控的目的&#xff1a; 一、数据上报方式 本文的方案是&#xff0c;优先navigator.sendBeacon&#xff0c;降级使用1x1像素gif图片…

网站建设中,JavaScript为什么现在可以做后台了?

JavaScript&#xff0c;作为一种最初为浏览器端脚本设计的语言&#xff0c;已经逐渐发展成为可以在服务器端运行的强大工具。以下是JavaScript可以做后台开发的原因分析&#xff1a; Node.js的崛起 事件驱动与非阻塞I/O&#xff1a;Node.js的事件驱动和非阻塞I/O模型使得JavaSc…

[WMCTF2020]Make PHP Great Again 2.01

又是php代码审计,开始吧. 这不用审吧&#xff0c;啊喂. 意思就是我们要利用require_once()函数和传入的file的value去读取flag的内容.&#xff0c;貌似呢require_once()已经被用过一次了&#xff0c;直接读取还不行&#xff0c;看一下下面的知识点. require_once() require…

2.1 HuggingFists系统架构(一)

系统架构 HuggingFists的前端主体开发语言为HtmlJavascript&#xff0c;后端的主体开发语言为Java。在算子部分有一定份额的Python代码&#xff0c;用于整合Python在数据处理方面强大能力。 功能架构 HuggingFists的功能架构如上&#xff0c;由下向上各层为&#xff1a; 数据存…

鸿蒙OpenHarmony【轻量系统芯片移植】轻量系统STM32F407芯片移植案例

轻量系统STM32F407芯片移植案例 介绍基于STM32F407IGT6芯片在拓维信息[Niobe407]开发板上移植OpenHarmony LiteOS-M轻量系统&#xff0c;提供交通、工业领域开发板解决方案。移植架构采用Board与SoC分离方案&#xff0c;使用arm gcc工具链Newlib C库&#xff0c;实现了lwip、l…

windows11环境安装lua及luarocks(踩坑篇)

一、lua安装及下载 官方地址&#xff1a; Lua Binaries Download 从这里就有坑了&#xff0c;下载后先解压win64_bin.zip&#xff0c;之后解压lib&#xff0c;用lib中的文件替换win64的&#xff0c;并把include文件夹复制过去&#xff0c;之后复制并重命名lua54&#xff0c;方…

初识Jenkins持续集成系统

随着软件开发复杂度的不断提高&#xff0c;团队成员之间如何更好地协同工作以确保软件开发的质量&#xff0c;已经慢慢成为开发过程中不可回避的问题。Jenkins 自动化部署可以解决集成、测试、部署等重复性的工作&#xff0c;工具集成的效率明显高于人工操作;并且持续集成可以更…

【JVM原理】运行时数据区(内存结构)

JVM &#xff08;Java Virtual Machine&#xff09;原理 文章目录 四、运行时数据区&#xff08;内存结构&#xff09;4-1 线程私有区域程序计数器&#xff08;program counter Register&#xff09;本地方法栈&#xff08;Native Method Stacks&#xff09;Java 虚拟机栈&…

探索MemGPT:AI界的新宠儿

文章目录 探索MemGPT&#xff1a;AI界的新宠儿1. 背景介绍2. MemGPT是什么&#xff1f;3. 如何安装MemGPT&#xff1f;4. 简单的库函数使用方法5. 场景应用场景一&#xff1a;创建持久聊天机器人场景二&#xff1a;文档分析场景三&#xff1a;多会话聊天互动 6. 常见Bug及解决方…

HTML中的表单(超详细)

一、表单 1.语法 <!-- action&#xff1a;提交的地方 method&#xff1a;提交的方式&#xff08;get会显示&#xff0c;post不会&#xff09; --> <form action"#" method"get"><p>名字&#xff1a;<input name"name" ty…

关联式容器——map与set

map与set map与set的使用序列式容器与关联式容器概念序列式容器 (Sequence Containers)常见的序列式容器&#xff1a; 关联式容器 (Associative Containers)常见的关联式容器&#xff1a; set的定义与使用set类的介绍set的构造和迭代器set的增删查&#xff08;无改&#xff09;…

【多线程】面试高频考点!JUC常见类的详细总结,建议收藏!

&#x1f490;个人主页&#xff1a;初晴~ &#x1f4da;相关专栏&#xff1a;多线程 / javaEE初阶 JUC是“Java Util Concurrency”的缩写&#xff0c;指的是Java并发工具包&#xff0c;它位于java.util.concurrent包及其子包中。JUC包提供了大量用于构建并发应用程序的工具和…

ARM基础

一、ARM ARM公司&#xff08;正式名称为ARM Holdings Ltd.&#xff09;是一家总部位于英国剑桥的半导体和软件设计公司&#xff0c;专注于开发和授权基于ARM架构的处理器技术。 ARM也是一种广泛使用的计算机架构&#xff0c;特别适合于低功耗和高性能的应用。ARM最初由英国的Ac…

【Redis】分布式锁之 Redission

一、基于setnx实现的分布式锁问题 重入问题&#xff1a;获得锁的线程应能再次进入相同锁的代码块&#xff0c;可重入锁能防止死锁。例如在HashTable中&#xff0c;方法用synchronized修饰&#xff0c;若在一个方法内调用另一个方法&#xff0c;不可重入会导致死锁。而synchroni…

WebGL入门(一)绘制一个点

源码&#xff1a; <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>Document</title><scr…

2-103 基于matlab的光电信号下血氧饱和度计算

基于matlab的光电信号下血氧饱和度计算&#xff0c;光转换成电信号时&#xff0c;由于动脉对光的吸收有变化而其他组织对光的吸收基本不变&#xff0c;得到的信号就可以分为直流DC信号和交流AC信号。提取AC信号&#xff0c;就能反应出血液流动的特点。这种技术叫做光电容积脉搏…

STM32基础学习笔记-Timer定时器面试基础题5

第五章、TIMER 常见问题 1、基本概念&#xff1a;什么是定时器 &#xff1f;作用 &#xff1f;分类 &#xff1f; 2、时基单元 &#xff1f;组成 &#xff1f;计数模式 &#xff1f;溢出条件 &#xff1f; 溢出时间计算 &#xff1f; 3、systick原理 &#xff1f;代码讲解 &…