1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Node: __slots__ = 'son', 'end'
def __init__(self): self.son = {} self.end = False
class Trie: def __init__(self): self.root = Node()
def insert(self, word: str) -> None: cur = self.root for c in word: if c not in cur.son: cur.son[c] = Node() cur = cur.son[c] cur.end = True
def find(self, word: str) -> int: cur = self.root for c in word: if c not in cur.son: return 0 cur = cur.son[c] return 2 if cur.end else 1
def search(self, word: str) -> bool: return self.find(word) == 2
def startsWith(self, prefix: str) -> bool: return self.find(prefix) != 0
|