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
相关推荐
大江东去浪淘尽千古风流人物7 分钟前
【Python】第三方库的功能简介
开发语言·python
坐忘3GQ11 分钟前
65.Python-web框架-Django-免费模板django-datta-able的admin_datta
后端·python·django·templates·datta able·admin_datta
HZ3557212 分钟前
智谱AI: ChatGLM API的使用
python·自然语言处理
PhoenixAI821 分钟前
AI绘画-Stable Diffusion 原理介绍及使用
人工智能·python·机器学习·ai作画·stable diffusion
2301_7969821424 分钟前
pycharm中新建的临时python文件存放在哪里?
ide·python·pycharm
U盘失踪了25 分钟前
Django 多对多关系
python·django
EthanWsir27 分钟前
C语言力扣刷题8——环形链表——[快慢双指针, 龟兔赛跑]
c语言·leetcode·链表
eclipsercp34 分钟前
《每天5分钟用Flask搭建一个管理系统》 第7章:用户认证
后端·python·flask
小尤笔记1 小时前
Python知识点背诵手册,超详细知识梳理
开发语言·python·学习·python入门·学习手册
经海路大白狗1 小时前
开启IT世界的第一步:高考新生的暑期学习指南
前端·后端·python·学习·高考