【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. 最简单的JVM内存结构图

    JVM内存结构图 大家好,好几天没有更新了,今天的内容有点多,我们详细介绍下JVM内部结构图,还是和之前一样,案例先行,方便大家理解记忆. /** * @author :jiaolian * @dat ...

  2. 10、Spring教程之整合MyBatis

    1.步骤 1.导入相关jar包 junit <dependency> <groupId>junit</groupId> <artifactId>juni ...

  3. 11、MyBatis教程之动态SQL

    12.动态SQL 1.介绍 什么是动态SQL:动态SQL指的是根据不同的查询条件 , 生成不同的Sql语句. 官网描述: MyBatis 的强大特性之一便是它的动态 SQL.如果你有使用 JDBC 或 ...

  4. unable to read askpass response from 'C:\Users\wxy\.IntelliJIdea2019.1\system\tmp\intellij-git-askpass.bat' bash: /dev/tty: No such device or address failed to execute prompt script (exit code 1)

    解决方法:

  5. sqli-labs系列——第三关

    less3 判断注入类型 这第三关有点意思,是一个带括号的数字型注入,这里需要闭合它的括号,之前遇到过很多这样的站,它的sql语句一般都是这样的: $sql = select * from user ...

  6. 错误提示:Access denied for user 'GC'@'localhost' (using password: YES)

    错误描述:使用的是C3P0连接池 Spring整合Mybatis时出现错误 java.sql.SQLException: Access denied for user 'GC'@'localhost' ...

  7. 对接快递100&聚水潭API

    对接快递100&聚水潭API 入我相思门,知我相思苦. 简介:对接第三方平台快递100&聚水潭API的简要总结. 1.感悟 个人感觉快递100的API更友好一些,比如有SDK可以调用: ...

  8. Istio 实践 之 Circuit breakers 断路器 (请求熔断)

    参考: https://blog.51cto.com/14625168/2499406 https://istio.io/latest/zh/docs/tasks/traffic-management ...

  9. 第23 章 : Kubernetes API 编程范式

    Kubernetes API 编程范式 需求来源 首先我们先来看一下 API 编程范式的需求来源. 在 Kubernetes 里面, API 编程范式也就是 Custom Resources Defi ...

  10. 下载kaggle数据集的小妙招

    kaggle是很多数据分析和机器学习初学者非常喜爱的数据科学竞赛平台. 这个平台上有很多接近现实业务场景的数据集,非常适合练手. 今天向大家推荐一个下载kaggle数据集的小工具--kaggleAPI ...