首页 > 编程语言 >208. 实现 Trie (前缀树)-python

208. 实现 Trie (前缀树)-python

时间:2024-05-06 11:11:57浏览次数:17  
标签:node search word Trie 208 self char python

Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。

请你实现 Trie 类:

Trie() 初始化前缀树对象。
void insert(String word) 向前缀树中插入字符串 word 。
boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。

示例:

输入
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
输出
[null, null, true, false, true, null, true]

解释
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 True
trie.search("app"); // 返回 False
trie.startsWith("app"); // 返回 True
trie.insert("app");
trie.search("app"); // 返回 True

头节点是空节点,然后每个节点存储一个字母

class Node:
    def __init__(self):
        self.children={}
        self.is_word=False

class Trie:

    def __init__(self):
        self.root=Node()


    def insert(self, word: str) -> None:
        node=self.root
        for char in word:
            if char not in node.children:
                node.children[char]=Node()
            node=node.children[char]
        node.is_word=True


    def search(self, word: str) -> bool:
        node=self.root
        for char in word:
            if char not in node.children:
                return False
            node=node.children[char]
        return node.is_word


    def startsWith(self, prefix: str) -> bool:
        node = self.root
        for char in prefix :
            if char not in node.children:
                return False
            node=node.children[char]
        return True



# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)

标签:node,search,word,Trie,208,self,char,python
From: https://www.cnblogs.com/donghao99/p/18174623

相关文章

  • 207. 课程表-python
    你这个学期必须选修numCourses门课程,记为0到numCourses-1。在选修某些课程之前需要一些先修课程。先修课程按数组prerequisites给出,其中prerequisites[i]=[ai,bi],表示如果要学习课程ai则必须先学习课程bi。例如,先修课程对[0,1]表示:想要学习课程0,你......
  • python雨滴数浓度计算
    前面已经将32×32的数据删除了不需要的列,数据变成了32×21的数据excel的粒径为了匹配txt的32行数据,我进行了重复复制,将excel变成下图: 那么采用数浓度公式:代码:#-*-coding:utf-8-*-"""@author:SuYue@file:shunongdu.py@time:2024/04/30@desc:"""importnumpya......
  • pipenv-基本使用手册 解决python包版本冲突
    https://pipenv.pypa.io/python使用pip安装包,默认都是在全局包,当A项目使用openai0.29,B项目使用openai1.10,这个时候,就会出现两个项目只能运行一个的情况。如果安装1.10,会把原来0.29的版本更新掉,导致原来A项目就运行不了。刚接触python,很好奇为啥没有像npm一样的......
  • python 打印 ASCII表
    ASCII表+------+------+------+------+---------------------------------+|Dec|Hex|Oct|Char|Description|+------+------+------+------+---------------------------------+|0|00|000||NUL(nullterminator)......
  • async await(python)
    简单记录一下asyncawait在Python中的用法以洗衣机洗衣服为例,假设有3台洗衣机,每台洗衣机都需要洗一些衣服一种做法就是依次启动每一台洗衣机,当一台洗衣机结束任务后,开始下一台fromtimeimportsleep,timedeflaundry():defwasher1():print('washeronebeg......
  • 利用python爬取某壳的房产数据
    以无锡的某壳为例进行数据爬取,现在房子的价格起伏很快,买房是人生一个大事,了解本地的房价走势来判断是否应该入手。(建议是近2年不买,本人在21年高位抛了一套房,基本是通过贝壳数据判断房价已经到顶,希望此爬虫能够帮到各位。)这里只爬了必看好房的数据,贝壳有放抓机制,无法跑全所有数据......
  • Mac更新python3.12 解决pip3安装报错
    Mac使用homebrew更新了python3.12,删除了以前的版本和pip3安装软件时候报错。error:externally-managed-environment×Thisenvironmentisexternallymanaged╰─>ToinstallPythonpackagessystem-wide,trybrewinstallxyz,wherexyzisthepackageyouare......
  • python交教程4:文件操作
    文件操作流程人类操作一个word流程:1、找到文件、双击打开2.读或修改3.保存&关闭⽤python操作⽂件也差不多: 只读模式 创建模式 追加模式 遍历文件 图片视频--二进制文件 其他方法 打开文件--混合模式 ......
  • 精通-Python-正则表达式(全)
    精通Python正则表达式(全)原文:zh.annas-archive.org/md5/3C085EA0447FEC36F167335BDBD4428E译者:飞龙协议:CCBY-NC-SA4.0前言自计算机科学迈出第一步以来,文本处理一直是最重要的话题之一。经过几十年的研究,我们现在拥有了最多才多艺和无处不在的工具之一:正则表达式。验证、......
  • Python全栈开发
    【Python初级】【一】计算机基础【二】编程语言和Python语言介绍【三】Python解释器和Pycharm的按照【四】常量和变量【五】垃圾回收机制【六】基本数据类型【七】程序与用户交互【八】基本运算符【九】流程控制语句【Python中级】【一】数据类型的内置方法【二】可变......