Trie

来自wrc's Wiki
Weirane讨论 | 贡献2021年10月15日 (五) 22:20的版本 (建立内容为“Category:刷题 字典树。 <syntaxhighlight lang=python> class Trie: def __init__(self): self.children = defaultdict(Trie) self.isword…”的新页面)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳到导航 跳到搜索

字典树。

class Trie:
    def __init__(self):
        self.children = defaultdict(Trie)
        self.isword = False

    def insert(self, word: str) -> None:
        """Inserts a word into the trie."""
        t = self
        for c in word:
            t = t.children[c]
        t.isword = True

    def search(self, word: str) -> bool:
        """Returns if the word is in the trie."""
        t = self
        for c in word:
            if c in t.children:
                t = t.children[c]
            else:
                return False
        return t.isword

    def startsWith(self, prefix: str) -> bool:
        """Returns if there is any word in the trie that starts with the given prefix."""
        t = self
        for c in prefix:
            if c in t.children:
                t = t.children[c]
            else:
                return False
        return True

相关题目

LeetCode 208. Implement Trie (Prefix Tree)