Python | Leetcode Python题解之第208题实现Trie(前缀树)

题目:

题解:

python 复制代码
class Trie:
    def __init__(self):
        self.children = [None] * 26
        self.isEnd = False
    
    def searchPrefix(self, prefix: str) -> "Trie":
        node = self
        for ch in prefix:
            ch = ord(ch) - ord("a")
            if not node.children[ch]:
                return None
            node = node.children[ch]
        return node

    def insert(self, word: str) -> None:
        node = self
        for ch in word:
            ch = ord(ch) - ord("a")
            if not node.children[ch]:
                node.children[ch] = Trie()
            node = node.children[ch]
        node.isEnd = True

    def search(self, word: str) -> bool:
        node = self.searchPrefix(word)
        return node is not None and node.isEnd

    def startsWith(self, prefix: str) -> bool:
        return self.searchPrefix(prefix) is not None
相关推荐
Terio_my13 分钟前
Python制作12306查票工具:从零构建铁路购票信息查询系统
开发语言·python·microsoft
万粉变现经纪人36 分钟前
如何解决 pip install -r requirements.txt 约束文件 constraints.txt 仅允许固定版本(未锁定报错)问题
开发语言·python·r语言·django·beautifulsoup·pandas·pip
站大爷IP42 分钟前
Python定时任务实战:APScheduler从入门到精通
python
Fairy_sevenseven1 小时前
[1]python爬虫入门,爬取豆瓣电影top250实践
开发语言·爬虫·python
ThisIsMirror1 小时前
CompletableFuture并行任务超时处理模板
java·windows·python
Young_Zn_Cu1 小时前
LeetCode刷题记录(持续更新中)
算法·leetcode
天选之女wow1 小时前
【代码随想录算法训练营——Day31】贪心算法——56.合并区间、738.单调递增的数字、968.监控二叉树
算法·leetcode·贪心算法
java1234_小锋2 小时前
TensorFlow2 Python深度学习 - TensorFlow2框架入门 - 计算图和 tf.function 简介
python·深度学习·tensorflow·tensorflow2
程序员晚枫2 小时前
Python 3.14新特性:Zstandard压缩库正式加入标准库,性能提升30%
python
逆境清醒2 小时前
VS Code配置Python开发环境系列(1)___VScode的安装 ,VScode常用快捷键
vscode·python·visual studio code