字典树-208. 实现 Trie (前缀树)-PYTHON

在这里插入图片描述

python利用字典结构的简便版本(注意看注释理解)

class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.lookup = {}   #构建一个字典结构,用于存储元素数据
        

    def insert(self, word):
        """
        Inserts a word into the trie.
        """
        tree = self.lookup   #给公共字典取别名
        for a in word:
            if a not in tree:
                tree[a] = {}   #逐元素提取字母到字典中查找是否存在,如果不存在就在字典内建立一个空的子字典
            tree = tree[a]   #跟踪标记位置变换,进入到字字典中进行操作
        # 单词结束标志
        tree["#"] = "#"   #插入单词结束在最后一个字字典中插入结束符
        print(self.lookup)
        

    def search(self, word):
        """
        Returns if the word is in the trie.
        """
        tree = self.lookup
        for a in word:
            if a not in tree: #{u'a': {u'p': {u'p': {'#': '#', u'l': {u'e': {'#': '#'}}}}}}
                return False  #层层深入子字典查找元素,形如上面结构,apple和app可以同时存在只不过在第二个p字母之后有了两个分支,可以结束也可以继续下一个字母l
            tree = tree[a]   #跟踪标记变换
        if "#" in tree:   #当遍历到最后一个匹配字母后,如果最后一个子字典中有#结束符标志那么代表存在该单词,如果没有那么就是现存单词还要更长,所以搜索失败
            return True
        return False
        

    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """
        tree = self.lookup
        for a in prefix:
            if a not in tree:
                return False  #缩减版的search操作,不用判断是否有结束,有前缀即可
            tree = tree[a]
        return True

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值