字典树。

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)