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
相关推荐
羲云网络31 分钟前
GPT Image 2.6 海报改横竖版:文字安全区、排版分离与交付验收
图像处理·人工智能·python·aigc
曲径海盗2 小时前
【Python 学习第 65 天】字典基础
python·学习笔记·编程入门
Wellijohn2 小时前
Docker 瘦身、手写 MCP、异步并发:被问得最多的 12 个问题,一次答完
python·docker·mcp
VW_4045 小时前
csdn-2026-11-23-第一站踩坑
爬虫·python
Navigator_Z5 小时前
LeetCode //C - 1318. Minimum Flips to Make a OR b Equal to c
c语言·算法·leetcode
yiangL_5 小时前
课后作业4:基于 Python 的古诗词词云可视化(P205)
开发语言·python
Dmz丶5 小时前
前端转 AI 100 天 Day 52:RAG 项目实战(一)——从零搭建企业知识库
python
驭渊的小故事9 小时前
LeetCode 33:搜索旋转排序数组——从二分查找到旋转数组的区间判定
算法·leetcode·职场和发展
卷无止境9 小时前
用 SimPy 做离散事件仿真:时钟不走步,事件自己排队
后端·python
撸码猿10 小时前
数据采集场景的语序点选验证码:90.2% 整词准确率的本地 OCR 实践
python·ocr