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
相关推荐
海兰3 分钟前
【 Python 量化交易】第6章:数据可视化
开发语言·python·信息可视化
多多鼠4 分钟前
Tool Calling的信任边界:从协议校验到执行沙箱的完整链路设计
运维·开发语言·网络·人工智能·python·langchain
Jazz_z20 分钟前
使用 Python 合并与取消合并 Excel 单元格
开发语言·python·excel
Lenyiin21 分钟前
第6篇_Python高级语法与标准库精髓:从会用到达精通
java·python·html
ZGG00327 分钟前
真题拆解 05:ReAct 还是 Plan-and-Execute——规划范式怎么选
python·agent·react
quantdash_cc36 分钟前
量化数据管道为什么会出现历史 K 线缺口?从 API 请求到数据质量的完整排查方法
开发语言·python·数据分析·量化·股票数据·quantdash
用户77833661321116 小时前
用 React Hook 封装搜索数据:useSerp 的防抖、缓存与错误处理
python·api
65岁退休Coder20 小时前
LangGraph v1.2.9 节点容错策略 & 流式输出 & 持久化记忆管理
后端·python·langchain
ikun_文1 天前
Django框架路由Router的使用
python·pycharm·django