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
相关推荐
SuperCandyXu20 分钟前
leetcode0310. 最小高度树-medium
数据结构·c++·算法·leetcode
有一个好名字44 分钟前
力扣:多数元素
算法·leetcode·职场和发展
小文数模1 小时前
2025数维杯数学建模C题完整分析参考论文(共36页)(含模型、可运行代码、数据)
python·数学建模·matlab
是梦终空1 小时前
Python毕业设计219—基于python+Django+vue的房屋租赁系统(源代码+数据库+万字论文)
python·django·vue·毕业设计·毕业论文·源代码·房屋租赁系统
Q_Q19632884751 小时前
python小区物业管理系统-小区物业报修系统
开发语言·spring boot·python·django·flask·node.js·php
小小毛桃1 小时前
使用PyTorch训练马里奥强化学习代理的完整指南
人工智能·pytorch·python
yuanpan2 小时前
平面坐标系中判断点P是否在线段上AB上的常用方法总结
开发语言·python·平面·点线关系
海拥✘2 小时前
用Python监控金价并实现自动提醒!附完整源码
开发语言·python
王大傻09282 小时前
python实现点餐系统
python
知识中的海王2 小时前
猿人学web端爬虫攻防大赛赛题第7题——动态字体,随风漂移
爬虫·python