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
相关推荐
用户617433273105 分钟前
Python 的 with ... as ... 上下文管理器
python
周周记笔记1 小时前
PyCharm的初始设置
ide·python·pycharm
2401_841495641 小时前
【语音识别】混合高斯模型
人工智能·python·算法·机器学习·语音识别·gmm·混合高斯模型
徐凤年lll2 小时前
python 初学2
开发语言·python
坚持就完事了2 小时前
解析数据练习(小项目)
python
周周记笔记3 小时前
Pycharm详解:高效Python开发的首选IDE
ide·python·pycharm
香辣西红柿炒蛋3 小时前
Python企业编码规范
python
夏鹏今天学习了吗3 小时前
【LeetCode热题100(57/100)】括号生成
算法·leetcode·职场和发展
三花聚顶<>3 小时前
310.力扣LeetCode_ 最小高度树_直径法_DFS
算法·leetcode·深度优先
努力学算法的蒟蒻3 小时前
day04(11.2)——leetcode面试经典150
算法·leetcode