LeetCode.208.前缀树

原题链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree/submissions/。
构建前缀树/字典树。下面我们学习一下字典树。
令S为一个来自字母表 ∑ \sum 的s个字符的集合。S的标准字典树是一个具有以下特性的有序数T.

  • 除了根之外的T的每个节点,都用 ∑ \sum 中的字符做标签。
  • T的内部节点的孩子节点有不同的标签
  • T的s个叶子节点,每一个叶子节点和S中的一个字符串相连,从根到T的一个叶子节点f的路径的标签串联产生了一个在S中的字符串。
    下面用一个例子来说明什么是字典树。
    在这里插入图片描述
    上图是一个字符串 { b e a r , b e l l , b i d , b u l l , b u y , s e l l , s t o c k , s t o p } \{ bear, bell, bid, bull, buy, sell, stock, stop\} {bear,bell,bid,bull,buy,sell,stock,stop}的标准字典树。
    下图是生成字典树的python程序:
from collections import defaultdict
class TrieNode: # 字典树的节点类
    def __init__(self):
        self.children = defaultdict(TrieNode)  # 孩子节点是值为列表的字典
        self.is_word = False   # 如果是叶子节点,那么这个值应该为True。代表了是字符串集中的一个字符串。
class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = TrieNode()  # 根节点
        

    def insert(self, word: str) -> None:
        """
        Inserts a word into the trie.
        """
        cur = self.root
        for char in word:
            cur = cur.children[char]
        cur.is_word = True
        
        

    def search(self, word: str) -> bool:
        """
        Returns if the word is in the trie.
        """
        cur = self.root
        for char in word:
            cur = cur.children.get(char)
            if not cur:
                return False
        return cur.is_word
        

    def startsWith(self, prefix: str) -> bool:
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """
        cur = self.root
        for char in prefix:
            cur = cur.children.get(char)
            if not cur:
                return False
        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)

不使用collection中defaultdict模块速度会更快。

class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = {}
        self.is_word = -1
    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """
        cur = self.root
        for char in word:
            if char not in cur:
                cur[char] = {}
            cur = cur[char]
        
        cur[self.is_word] = True
        

    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        cur = self.root
        for char in word:
            if char not in cur:
                return False
            cur = cur[char]
        if self.is_word not in cur:
            return False
        return True
        

    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        cur = self.root
        for char in prefix:
            if char not in cur:
                return False
            cur = cur[char]
        return True
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值