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
相关推荐
diediedei19 小时前
持续集成/持续部署(CI/CD) for Python
jvm·数据库·python
weixin_4454023019 小时前
Python游戏中的碰撞检测实现
jvm·数据库·python
放荡不羁的野指针19 小时前
leetcode150题-双指针
数据结构·算法·leetcode
棒棒的皮皮19 小时前
【OpenCV】Python图像处理矩特征之矩的计算/计算轮廓的面积
图像处理·python·opencv·计算机视觉
人工智能AI技术19 小时前
【Agent从入门到实践】41 部署方式选型:本地脚本、Docker容器、云服务部署
人工智能·python
Fleshy数模19 小时前
零基础玩转HTML:核心标签与页面构建
python·html
好学且牛逼的马19 小时前
【Hot100|15-LeetCode 238. 除自身以外数组的乘积】
数据结构·算法·leetcode
2401_8324027519 小时前
使用Docker容器化你的Python应用
jvm·数据库·python
七夜zippoe19 小时前
WebSocket实时通信系统构建:从握手协议到生产级实战
网络·python·websocket·网络协议·心跳
Tisfy19 小时前
LeetCode 3651.带传送的最小路径成本:动态规划
算法·leetcode·动态规划·题解·排序