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
相关推荐
浅念-4 分钟前
动态规划:线性DP——多状态DP与子数组专题笔记
c++·笔记·算法·leetcode·职场和发展·动态规划·力扣
ueotek24 分钟前
Ansys Zemax丨在 OpticStudio 中拟合折射率数据
python·软件工程·ansys·光学仿真·光学设计·zeamx
czq_268671948727 分钟前
Python打卡第40天
开发语言·python
不爱吃鱼的蔓热莓29 分钟前
Autosar之根据ARXML中报文信息生成SWC(二)
开发语言·python
奈葵32 分钟前
Python语句
开发语言·python
随性而行3601 小时前
企业微信API接口开发实战:如何实现消息回调接收与业务事件处理?
java·前端·python·微信·机器人·企业微信
言乐61 小时前
Python于LOLM针对伊泽瑞尔的数据分析
开发语言·python·机器学习·数据分析·pandas
打工仔折腾 AI1 小时前
Qt网络编程实战:UDP、TCP到HTTP的落地经验与选型
网络·人工智能·后端·python·qt·udp·ai agent 实战
打工仔折腾 AI1 小时前
SQL 编辑器不是高级记事本:KStudio 与 KSQL Developer 的建表与增删改查手法
数据库·人工智能·后端·python·sql·编辑器·ai agent 实战
学电子她就能回来吗1 小时前
LeetCode Hot 100|滑动窗口专题零基础学习笔记
笔记·学习·leetcode