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)

结果

解题步骤:

相关推荐
圣保罗的大教堂1 天前
leetcode 3650. 边反转的最小路径总成本 中等
leetcode
木井巳1 天前
【递归算法】验证二叉搜索树
java·算法·leetcode·深度优先·剪枝
We་ct1 天前
LeetCode 30. 串联所有单词的子串:从暴力到高效,滑动窗口优化详解
前端·算法·leetcode·typescript
历程里程碑1 天前
子串----和为K的子数组
大数据·python·算法·leetcode·elasticsearch·搜索引擎·哈希算法
YuTaoShao1 天前
【LeetCode 每日一题】2976. 转换字符串的最小成本 I
算法·leetcode·职场和发展
我是咸鱼不闲呀1 天前
力扣Hot100系列16(Java)——[堆]总结()
java·算法·leetcode
YuTaoShao1 天前
【LeetCode 每日一题】2977. 转换字符串的最小成本 II——(解法一)记忆化搜索
算法·leetcode·职场和发展
希望有朝一日能如愿以偿1 天前
力扣每日一题
数据结构·算法·leetcode
草履虫建模1 天前
力扣算法分析 27.移除元素
java·开发语言·数据结构·后端·算法·leetcode·排序算法
im_AMBER1 天前
Leetcode 109 链表的中间结点 | 删除链表的中间节点
数据结构·学习·算法·leetcode·链表