208. 实现 Trie (前缀树) - 力扣(LeetCode)

图示

代码

python 复制代码
# encoding = utf-8
# 开发者:Alen
# 开发时间: 15:26 
# "Stay hungry,stay foolish."

class TrieNode:
    def __init__(self):
        self.children = {}
        self.endOfWord = False

class Trie(object):
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        """
        :type word: str
        :rtype: None
        """
        cur = self.root

        for c in word:
            if c not in cur.children:
                cur.children[c] = TrieNode()
            cur = cur.children[c]
        cur.endOfWord = True

    def search(self, word):
        """
        :type word: str
        :rtype: bool
        """
        cur = self.root
        for c in word:
            if c not in cur.children:
                return False
            cur = cur.children[c]
        return cur.endOfWord


    def startsWith(self, prefix):
        """
        :type prefix: str
        :rtype: bool
        """
        cur = self.root
        for c in prefix:
            if c not in cur.children:
                return False
            cur = cur.children[c]
        return True


# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)

结果

解题步骤:

相关推荐
失去的青春---夕阳下的奔跑10 小时前
560. 和为 K 的子数组
数据结构·算法·leetcode
m0_6294947311 小时前
LeetCode 热题 100-----25.回文链表
数据结构·算法·leetcode·链表
吃着火锅x唱着歌13 小时前
LeetCode 1019.链表中的下一个更大节点
算法·leetcode·链表
凌波粒14 小时前
LeetCode--404.左叶子之和(二叉树)
算法·leetcode·职场和发展
绝知此事14 小时前
【算法突围 03】核心算法思想:分治/递归/动态规划与 LeetCode 高频真题解析
算法·leetcode·面试·动态规划
阿Y加油吧16 小时前
两道字符串 DP 模板题复盘:最长公共子序列 & 编辑距离
leetcode
我爱cope16 小时前
【力扣hot100:76. 最小覆盖子串】
算法·leetcode·职场和发展
sheeta199816 小时前
LeetCode 每日一题笔记 日期:2026.05.20 题目:2657. 找到前缀公共数组
笔记·算法·leetcode
吃着火锅x唱着歌17 小时前
LeetCode 962.最大宽度坡
算法·leetcode·职场和发展
凌波粒17 小时前
LeetCode--257. 二叉树的所有路径(二叉树)
算法·leetcode·职场和发展