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)

结果

解题步骤:

相关推荐
Cccp.1235 小时前
【leetcode】(七)前缀树和贪心算法
数据结构·leetcode·贪心算法
优质酸酸乳10 小时前
力扣100题之21合并两个有序链表
算法·leetcode·链表
旖旎夜光10 小时前
LeetCode 137 : 只出现一次的数字 II(位运算) —— 题解
c++·笔记·学习·算法·leetcode·力控
yi01111 小时前
LeetCode 134 加油站:从 双循环暴力 演变到 贪心
linux·算法·leetcode
yi01112 小时前
DAY 14: LeetCode 394. 字符串解码|递归和栈到底怎么处理嵌套?
数据结构·笔记·python·算法·leetcode
P.D.Wei13 小时前
[Leetcode 1614] 括号的最大嵌套深度
算法·leetcode·职场和发展
blxr_13 小时前
力扣hot100寻找重复数https://leetcode.cn/problems/find-the-duplicate-number/
算法·leetcode·职场和发展
_不会dp不改名_14 小时前
leetcode_1614嵌套括号的最大深度
算法·leetcode·职场和发展
alphaTao17 小时前
LeetCode 每日一题 2026/9/21-2026/9/27
python·算法·leetcode
Persistent的粽子!1 天前
双指针算法:最大盛水容器
c++·算法·leetcode