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
相关推荐
小徐Chao努力9 分钟前
Leetcode-146.LRU缓存
java·leetcode
m0_3713561516 分钟前
【测试语言基础篇】Python基础之List列表
开发语言·python·list
Joyner201844 分钟前
python-leetcode-递增的三元子序列
算法·leetcode·职场和发展
大0马浓1 小时前
训练大模型LLM选择哪种开发语言最好
人工智能·python·训练
风筝超冷1 小时前
AttributeError: module ‘backend_interagg‘ has no attribute ‘FigureCanvas‘
python
onejason1 小时前
如何利用爬虫获取腾讯新闻详情数据:实战指南
前端·python
yicode1 小时前
Python基础:列表与元组详解
后端·python
梦丶晓羽2 小时前
自然语言处理:无监督朴素贝叶斯模型
人工智能·python·自然语言处理·tf-idf·贝叶斯定理·词袋模型·无监督朴素贝叶斯模型
Y雨何时停T2 小时前
使用 Python 批量提取 PDF 书签:一款实用工具的实现
python·pdf