题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,就是给一个字符串数组,并且逐个做 insert 或者 search 操作,还有判断搜索是否为前缀。

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
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
36
37
38
39
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


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