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
相关推荐
小陳参上19 小时前
用Python创建一个Discord聊天机器人
jvm·数据库·python
minstbe21 小时前
IC设计私有化AI助手实战:基于Docker+OpenCode+Ollama的数字前端综合增强方案(进阶版)
人工智能·python·语言模型·llama
zyq99101_11 天前
优化二分查找:前缀和降复杂度
数据结构·python·蓝桥杯
qyzm1 天前
天梯赛练习(3月13日)
开发语言·数据结构·python·算法·贪心算法
逆境不可逃1 天前
LeetCode 热题 100 之 64. 最小路径和 5. 最长回文子串 1143. 最长公共子序列 72. 编辑距离
算法·leetcode·动态规划
Qt学视觉1 天前
AI2-Paddle环境搭建
c++·人工智能·python·opencv·paddle
廋到被风吹走1 天前
【LangChain4j】特点功能及使用场景
后端·python·flask
Eward-an1 天前
LeetCode 239. 滑动窗口最大值(详细技术解析)
python·算法·leetcode
一叶落4381 天前
LeetCode 50. Pow(x, n)(快速幂详解 | C语言实现)
c语言·算法·leetcode
喵手1 天前
Python爬虫实战:用代码守护地球,追踪WWF濒危物种保护动态!
爬虫·python·爬虫实战·濒危物种·零基础python爬虫教学·wwf·濒危物种保护动态追踪