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
相关推荐
明月看潮生17 分钟前
青少年编程与数学 02-016 Python数据结构与算法 12课题、递归
python·算法·青少年编程·编程与数学
批量小王子24 分钟前
批量统一图像色彩
python
自在如风。1 小时前
Java 设计模式:装饰者模式详解
java·python·设计模式
大模型真好玩1 小时前
不写一行代码! VsCode+Cline+高德地图MCP Server 帮你搞定和女友的出行规划(附原理解析)
人工智能·python·mcp
再玩一会儿看代码1 小时前
pip 与 conda 的全面比较:Python 包管理的深度解析
经验分享·笔记·python·conda·课程设计·pip
Clocky71 小时前
opencv-python基础
开发语言·python
满怀10152 小时前
【Python Requests 库详解】
开发语言·python
不吃洋葱.2 小时前
力扣448.找到数组中所有消失的元素
数据结构·算法·leetcode
小白教程2 小时前
Python爬取视频的架构方案,Python视频爬取入门教程
python·架构·音视频·python爬虫·python视频爬虫·python爬取视频教程
仰望星空的小随3 小时前
django相关面试题
python·django·sqlite