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)

结果

解题步骤:

相关推荐
土司大王4 小时前
LeetCode hot100——缺失的第一个正数
数据结构·算法·leetcode
Cccp.1234 小时前
【leetcode】(二)认识O(NlogN)的排序
算法·leetcode
鹿角片ljp5 小时前
LeetCode 56:合并区间复盘|从排序思维到 List<int[]> 的简洁写法
算法·leetcode·list
玖玥拾6 小时前
LeetCode 205 同构字符串
算法·leetcode
_不会dp不改名_9 小时前
leetcode3875_构造奇偶一致的数组 I
leetcode
圣保罗的大教堂17 小时前
leetcode 1406. 石子游戏 III 困难
leetcode
带多刺的玫瑰1 天前
Leecode#15刷题之三数之和
算法·leetcode·职场和发展
圣保罗的大教堂1 天前
leetcode 877. 石子游戏 中等
leetcode
shehuiyuelaiyuehao1 天前
算法32,连续数组,前缀和+哈希表
算法·leetcode·职场和发展
Navigator_Z1 天前
LeetCode //C - 1223. Dice Roll Simulation
c语言·算法·leetcode