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)

结果

解题步骤:

相关推荐
Ricky111zzz1 天前
leetcode学python记录1
python·算法·leetcode·职场和发展
逆境不可逃2 天前
LeetCode 热题 100 之 230. 二叉搜索树中第 K 小的元素 199. 二叉树的右视图 114. 二叉树展开为链表
算法·leetcode·职场和发展
wfbcg2 天前
每日算法练习:LeetCode 15. 三数之和 ✅
算法·leetcode·职场和发展
y = xⁿ2 天前
【LeetCode Hot100】双指针:分离指针
算法·leetcode
6Hzlia2 天前
【Hot 100 刷题计划】 LeetCode 41. 缺失的第一个正数 | C++ 原地哈希题解
c++·leetcode·哈希算法
小肝一下2 天前
每日两道力扣,day6
数据结构·c++·算法·leetcode·双指针·hot100
人道领域2 天前
【LeetCode刷题日记】242.字母异位词
算法·leetcode·职场和发展
XWalnut2 天前
LeetCode刷题 day8
算法·leetcode·职场和发展
Ricky111zzz2 天前
leetcode学python记录2
python·算法·leetcode·职场和发展
会编程的土豆2 天前
【数据结构与算法】堆排序
开发语言·数据结构·c++·算法·leetcode