首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Leetcode Python 208。实现Trie (前缀树)

Leetcode Python 208。实现Trie (前缀树)
EN

Stack Overflow用户
提问于 2018-10-29 03:23:53
回答 2查看 2.1K关注 0票数 0

有人能说出我的代码出了什么问题吗?它通过了所有的测试用例,除了最后一个测试用例。当我下载特定的测试用例时,预期输出和实际输出似乎是一样的,问题是https://leetcode.com/problems/implement-trie-prefix-tree/description/

编辑1:代码如下:

代码语言:javascript
复制
class Trie:

def __init__(self):
    """
    Initialize your data structure here.
    """
    self.data = None
    self.children = {}
    self.isWord = False

def insert(self, word):
    """
    Inserts a word into the trie.
    :type word: str
    :rtype: void
    """
    if len(word) == 0:
        return
    if word[0] not in self.children:
        self.children[word[0]] = Trie()
        self.insertHelper(word[1:], self.children[word[0]])
    else:
        self.insertHelper(word[1:], self.children[word[0]])

    if len(word) == 1:
        self.isWord = True

def insertHelper(self, word, trie):
    if len(word) == 0:
        return

    if word[0] not in trie.children:
        trie.children[word[0]] = Trie()
        trie.insertHelper(word[1:], trie.children[word[0]])
    else:
        trie.insertHelper(word[1:], trie.children[word[0]])

    if len(word) == 1:
        trie.isWord = True





def search(self, word):
    """
    Returns if the word is in the trie.
    :type word: str
    :rtype: bool
    """
    if len(word) == 1 and word[0] in self.children and self.isWord:
        return True
    elif len(word) == 0:
        return False

    if word[0] in self.children:
        return self.searchHelper(word[1:], self.children[word[0]])
    else:
        return False

def searchHelper(self, word, trie):
    if len(word) == 1 and word[0] in trie.children and trie.isWord:
        return True
    elif len(word) == 0:
        return False

    if word[0] in trie.children:
        return self.searchHelper(word[1:], trie.children[word[0]])
    else:
        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
    """
    if len(prefix) == 0:
        return False
    if prefix[0] in self.children:
        return self.startsWithHelper(prefix[1:], self.children[prefix[0]])
    else:
        return False

def startsWithHelper(self, prefix, trie):
    if len(prefix) == 0:
        return True

    if prefix[0] in trie.children:
        return trie.startsWithHelper(prefix[1:], trie.children[prefix[0]])
    else:
        return False

提前谢谢。

EN

回答 2

Stack Overflow用户

发布于 2018-10-29 13:00:34

我注意到的一个怪癖是将一个空的前缀传递给startsWith()。如果此方法是在Python str方法startswith()上建模的,那么我们需要True

代码语言:javascript
复制
>>> "apple".startswith("")
True
>>>

但是在这种情况下,你的Trie返回False

代码语言:javascript
复制
>>> t = Trie()
>>> t.insert("apple")
>>> t.startsWith("")
False
>>>

下面是我对你的代码的修改,我主要是为了理解它,但我也发现你有冗余,特别是你的Helper函数。这段代码修复了上面提到的怪癖,并且是Python 3特有的:

代码语言:javascript
复制
class Trie:

    def __init__(self):
        self.children = {}
        self.isWord = False

    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str (or list internally upon recursion)
        :rtype: None
        """

        if not word:
            return

        head, *tail = word

        if head not in self.children:
            self.children[head] = Trie()

        trie = self.children[head]

        if tail:
            trie.insert(tail)
        else:
            self.isWord = True

    def search(self, word):
        """
        Returns True if the word is in the trie.
        :type word: str (or list internally upon recursion)
        :rtype: bool
        """

        if not word:
            return False

        head, *tail = word

        if head in self.children:
            if not tail and self.isWord:
                return True

            return self.children[head].search(word[1:])

        return False

    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie that starts with the given prefix.
        :type prefix: str (or list internally upon recursion)
        :rtype: bool
        """

        if not prefix:
            return True

        head, *tail = prefix

        if head in self.children:
            return self.children[head].startsWith(tail)

        return False
票数 2
EN

Stack Overflow用户

发布于 2021-03-22 04:28:29

这是另一个解决方案,它使用集合模块中的“defaultdictionary”在“insert”函数中使用递归。

图片来源:https://leetcode.com/problems/implement-trie-prefix-tree/discuss/631957/python-elegant-solution-no-nested-dictionaries

代码语言:javascript
复制
class Trie:

def __init__(self):
    """
    Initialize your data structure here.
    """
    self.nodes = collections.defaultdict(Trie)
    self.is_word = False

def insert(self, word: str) -> None:
    """
    Inserts a word into the trie.
    """
    if not word:
        self.is_word = True
    else:
        self.nodes[word[0]].insert(word[1:])
    

def search(self, word: str) -> bool:
    """
    Returns if the word is in the trie.
    """
    if not word:
        return self.is_word
    if word[0] in self.nodes:
        return self.nodes[word[0]].search(word[1:])
                
    return False
    
def startsWith(self, prefix: str) -> bool:
    """
    Returns if there is any word in the trie that starts with the given prefix.
    """
    if not prefix:
        return True
    
    if prefix[0] in self.nodes:
        return self.nodes[prefix[0]].startsWith(prefix[1:])
    
    return False

你的Trie对象将被实例化,并被这样调用:

代码语言:javascript
复制
obj = Trie()
obj.insert(word)
param_2 = obj.search(word)
param_3 = obj.startsWith(prefix)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53035282

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档