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

假装没事ソ 提交于 2020-02-17 14:42:17

在这里插入图片描述

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!