美文网首页
208. Implement Trie (Prefix Tree

208. Implement Trie (Prefix Tree

作者: JERORO_ | 来源:发表于2018-07-03 22:38 被阅读0次

问题描述

Implement a trie with insert, search, and startsWith methods.

思路

用Dictionary做,用嵌套dictionary的方法实现
对于一个单词中的每个字母,存为key,而value则是新建的dictionary,里面存放以下一个字母作为key、新建的dictionary作为value,以此类推,并用特殊符号标记出单词结尾
例如,insert('cjh'), 就会得到{'c': {'j': {'h': {'$': '$'}}}}


    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = {}

    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """
        curDict = self.root
        for x in word:
            if x not in curDict:
                curDict[x] = {}
            curDict = curDict[x]
        curDict['$'] = '$'
        # print(self.root)

    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        curDict = self.root
        for i in word:
            if i not in curDict:
                return False
            curDict = curDict.get(i)
        if '$' in curDict:
            return True
        return False

    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        curDict = self.root
        for i in prefix:
            if i not in curDict:
                return False
            curDict =curDict.get(i)
        return True

参考

https://leetcode.com/problems/implement-trie-prefix-tree/discuss/130893/Python-184ms-beats-100

相关文章

网友评论

      本文标题:208. Implement Trie (Prefix Tree

      本文链接:https://www.haomeiwen.com/subject/rycsuftx.html