力扣 208. 前缀树

字典树

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
33
34
35
class Tree:
def __init__(self, val):
self.val = val
self.next = {}

class Trie:

def __init__(self):
self.tree = Tree(0)

def insert(self, word: str) -> None:
tree = self.tree
for w in word:
if w not in tree.next.keys():
tree.next[w] = Tree(w)

tree = tree.next[w]
tree.next[-1] = True

def search(self, word: str) -> bool:
tree = self.tree
for w in word:
if w not in tree.next:
return False
tree = tree.next[w]

return tree.next.get(-1, False)

def startsWith(self, prefix: str) -> bool:
tree = self.tree
for w in prefix:
if w not in tree.next:
return False
tree = tree.next[w]
return True
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022 eightyninth
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信