这个 trie 实现有什么问题吗

2022-05-01 17:58:35 +08:00
 roundRobin

leetcode208 很简单的 trie 实现,下面这个 case 在 debug 的时候都是结果是[null, false],但是 submit 之后结果就变成了[null,true],是哪部分代码触发了服务器的异常编译吗?

class Trie:
    def __init__(self):
        self.root = Node()

    def insert(self, word: str) -> None:
        ptr = self.root
        for ch in word:
            if ch not in ptr.child:
                ptr.child[ch] = Node("")
            if ch == word[-1]:
                ptr.child[ch].val = ch
                return
            ptr = ptr.child[ch]

    def search(self, word: str) -> bool:
        ptr = self.root
        for ch in word:
            if ch not in ptr.child:
                return False
            ptr = ptr.child[ch]
        return ptr.val == word[-1]

    def startsWith(self, prefix: str) -> bool:
        ptr = self.root
        for ch in prefix:
            if ch not in ptr.child:
                return False
            ptr = ptr.child[ch]
        return True
    
class Node:
    def __init__(self, val="", child={}):
        self.child = child
        self.val = val


# 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)

Input:

["Trie","startsWith"]
[[],["a"]]

Output:

[null,true]

Expect:

[null,false]
1470 次点击
所在节点    Python
2 条回复
lixiang2017
2022-05-01 19:24:46 +08:00
insert 里逻辑不对。第二个 if 是干啥的,错的很离谱
ccvzz
2022-05-01 19:53:01 +08:00
bug 不止一个。你说的问题是因为:

```python
class Node:
def __init__(self, c={}):
self.c = c

n1 = Node()
n2 = Node()
n1.c is n2.c # True
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/850396

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX