【python】Leetcode每日一题-前缀树(Trie)

【题目描述】

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

请你实现 Trie 类:

Trie() 初始化前缀树对象。

void insert(String word) 向前缀树中插入字符串 word

boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回false

boolean startsWith(String prefix) 如果之前已经插入的字符串word的前缀之一为 prefix ,返回 true ;否则,返回 false

示例1:

输入
["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

提示:

1 <= word.length, prefix.length <= 2000
word 和 prefix 仅由小写英文字母组成
insert、search 和 startsWith 调用次数 总计 不超过 3 * 10^4 次

【分析】

  • 前缀树(Trie)️重要

    一图解千愁:

  • 代码

class Trie(object):
N = 100009
def __init__(self):
"""
Initialize your data structure here.
"""
self.trie = [[0] * self.N for i in range(26)]
self.count = [0] * self.N
self.index = 0 def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: None
"""
p = 0
for i in range(len(word)):
u = ord(word[i]) - ord('a')
if self.trie[u][p] == 0:
self.index += 1
self.trie[u][p] = self.index
p = self.trie[u][p]
self.count[p] += 1 def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
p = 0
for i in range(len(word)):
u = ord(word[i]) - ord('a')
if self.trie[u][p] == 0:
return False
p = self.trie[u][p]
return self.count[p] != 0 def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
p = 0
for i in range(len(prefix)):
u = ord(prefix[i]) - ord('a')
if self.trie[u][p] == 0:
return False
p = self.trie[u][p]
return True
  • 另外看到高赞题解,学习到还有一种二维数组法

    有需要的可以直接看原解,不过时间复杂度和空间复杂度都大很多。

【python】Leetcode每日一题-前缀树(Trie)的更多相关文章

  1. 【python】Leetcode每日一题-寻找旋转排序数组中的最小元素

    [python]Leetcode每日一题-寻找旋转排序数组中的最小元素 [题目描述] 已知一个长度为 n 的数组,预先按照升序排列,经由 1 到 n 次 旋转 后,得到输入数组.例如,原数组nums ...

  2. 【python】Leetcode每日一题-删除有序数组中的重复项

    [python]Leetcode每日一题-删除有序数组中的重复项 [题目描述] 给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 最多出现一次 ,返回删除后数组的新长度. 不要 ...

  3. 【python】Leetcode每日一题-存在重复元素3

    [python]Leetcode每日一题-存在重复元素3 [题目描述] 给你一个整数数组 nums 和两个整数 k 和 t .请你判断是否存在 两个不同下标 i 和 j,使得 abs(nums[i] ...

  4. 【python】Leetcode每日一题-扰乱字符串

    [python]Leetcode每日一题-扰乱字符串 [题目描述] 使用下面描述的算法可以扰乱字符串 s 得到字符串 t : 如果字符串的长度为 1 ,算法停止 如果字符串的长度 > 1 ,执行 ...

  5. 【python】Leetcode每日一题-打家劫舍2

    [python]Leetcode每日一题-打家劫舍2 [题目描述] 你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金.这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋 ...

  6. 【python】Leetcode每日一题-二叉搜索树节点最小距离

    [python]Leetcode每日一题-二叉搜索树节点最小距离 [题目描述] 给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 . 示例1: 输入:root = [4 ...

  7. 【python】Leetcode每日一题-最大数

    [python]Leetcode每日一题-最大数 [题目描述] 给定一组非负整数 nums,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数. 注意:输出结果可能非常大,所以你需要返回一个 ...

  8. 【python】Leetcode每日一题-丑数2

    [python]Leetcode每日一题-丑数2 [题目描述] 给你一个整数 n ,请你找出并返回第 n 个 丑数 . 丑数 就是只包含质因数 2.3 和/或 5 的正整数. 示例1: 输入:n = ...

  9. 【python】Leetcode每日一题-丑数

    [python]Leetcode每日一题-丑数 [题目描述] 给你一个整数 n ,请你判断 n 是否为 丑数 .如果是,返回 true :否则,返回 false . 丑数 就是只包含质因数 2.3 和 ...

随机推荐

  1. C# 基础 - 堆栈跟踪使用

    使用一:可用于捕获报错时. using System.Diagnostics; ... StackTrace st = new StackTrace(true); string stackIndent ...

  2. pip安装更新模块,以及执行更新所有模块

    moudle_name:是对应的模块名:请自行更换为自己需要更新的模块名 查看所有可更新的模块: pip list --outdated 更新某一个模块: pip install --upgrade ...

  3. css3中的渐变效果

    大家好,这里是demo软件园,今天为大家分享的是css3中的渐变效果. css3中的渐变需要注意的是渐变的是图片而不是颜色,而渐变又分为两种:线性渐变与径向渐变,今天我们重点介绍的是线性渐变. 1.线 ...

  4. PTE 准备之 Read aloud

    Read aloud A text appears on screen.Read the text aloud rext up tp 60 words varies by task, dependin ...

  5. ACM常用的C++ && STL

    内容 c++输入输出 c++ string vector:不定长数组 map:映射 queue:队列 sort:排序 priority_queue:优先队列 c++输入输出 1 #include &l ...

  6. golang 遍历树状结构

    以遍历Block结构为例,Block结构如下: type Block struct { Inside bool Nest int Boundary bool Incise []*Block } 可以看 ...

  7. springboot系列四:springboot整合mybatis jsp

    一.用IDEA 创建maven项目 项目目录结构 1.添加pom jar依赖 <?xml version="1.0" encoding="UTF-8"?& ...

  8. Python中树的遍历-堆排序

    1.二叉树的遍历 遍历:迭代所有元素一遍. 树的遍历:对树中所有的元素不重复的访问一遍,也成扫描 广度优先遍历:层序遍历 深度优先遍历:前序.中序.后续遍历. 遍历序列:将树中所有元素遍历一遍后,得到 ...

  9. 解决unbutu网络编程socket_tcp连接不上网络助手

    unbutu开放指定端口 开放端口8080 sudo iptables -I INPUT -p tcp --dport 8080 -j ACCEPT 保存设置 iptables-save 在终端中输入 ...

  10. Java例题_26 请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续 判断第二个字母。

    1 /*26 [程序 26 求星期] 2 题目:请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续 判断第二个字母. 3 程序分析:用情况语句比较好,如果第一个字母一样,则判断用情 ...