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
相关推荐
精灵vector1 小时前
LLMCompiler:基于LangGraph的并行化Agent架构高效实现
人工智能·python·langchain
1白天的黑夜11 小时前
哈希表-49.字母异位词分组-力扣(LeetCode)
c++·leetcode·哈希表
java1234_小锋1 小时前
Scikit-learn Python机器学习 - 特征降维 压缩数据 - 特征选择 - 移除低方差特征(VarianceThreshold)
python·机器学习·scikit-learn
万邦科技Lafite1 小时前
实战演练:通过API获取商品详情并展示
大数据·数据库·python·开放api接口
愈努力俞幸运2 小时前
uv教程 虚拟环境
python·uv
IMER SIMPLE2 小时前
人工智能-python-深度学习-经典网络模型-LeNets5
人工智能·python·深度学习
企业软文推广2 小时前
奥迪A5L×华为:品牌营销视角下的燃油车智能突围战!
python·华为
愚润求学2 小时前
【贪心算法】day7
c++·算法·leetcode·贪心算法
Pocker_Spades_A2 小时前
Python快速入门专业版(十五):数据类型实战:用户信息录入程序(整合变量、输入与类型转换)
数据库·python