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
相关推荐
后台模板学习16 分钟前
大模型 Prompt 工程在电商订单系统中的踩坑记录
java·python·prompt
2601_9679873730 分钟前
如何运行 Python 代码
python·最佳实践·脚本文件·代码运行·交互式环境
WiKiLeaks_successor31 分钟前
重构Time库的抽象设计
python·重构
AI源码40 分钟前
基于 Python 的短视频用户行为分析系统
开发语言·python
第九序言T1 小时前
数据分析岗 Pandas 面试题 20 道(上):概念与读代码
python·数据分析·pandas·数据处理
Dmz丶1 小时前
前端转 AI 100 天 Day 37:Few-shot 与 CoT——让模型学会“推理”
python
孟健1 小时前
我用Grok Bot本地剪口播视频,3段提示词搞定气口切除、字幕与封面
人工智能·python·aigc
2601_966949652 小时前
如何封装 qd.klines.batch(),让批量 K 线查询函数在多个策略中复用?
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
神仙别闹3 小时前
基于Python实现英词语自动对齐系统
开发语言·python
老歌老听老掉牙4 小时前
圆柱端面四平面交线及其在yoz面投影的几何解析与 Python 实现
开发语言·python·平面