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)

结果

解题步骤:

相关推荐
Pniubi39 分钟前
力扣73 矩阵置零
算法·leetcode·矩阵
文丑颜不良啊17 小时前
LeetCode2261~2280题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2241~2260题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2321~2340题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z2 天前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
文丑颜不良啊2 天前
LeetCode2161~2180题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2141~2160题目解析
java·leetcode
Dream it possible!3 天前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊3 天前
算法之双指针系列(一)
算法·leetcode