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)

结果

解题步骤:

相关推荐
iAkuya8 小时前
(leetcode)力扣100 36二叉树的中序遍历(迭代递归)
算法·leetcode·职场和发展
wangwangmoon_light8 小时前
1.1 LeetCode总结(线性表)_枚举技巧
算法·leetcode·哈希算法
有一个好名字9 小时前
力扣-小行星碰撞
算法·leetcode·职场和发展
栈与堆10 小时前
LeetCode-1-两数之和
java·数据结构·后端·python·算法·leetcode·rust
求梦82010 小时前
【力扣hot100题】反转链表(18)
算法·leetcode·职场和发展
求梦82011 小时前
【力扣hot100题】移动零(1)
算法·leetcode·职场和发展
练习时长一年11 小时前
LeetCode热题100(爬楼梯)
算法·leetcode·职场和发展
梭七y12 小时前
【力扣hot100题】(133)LRU缓存
leetcode·缓存·哈希算法
im_AMBER13 小时前
Leetcode 100 在链表中插入最大公约数
数据结构·c++·笔记·学习·算法·leetcode·链表