Trie树记录

简介

Trie树,又叫字典树,前缀树,是一种用途很广的数据结构,主要用于字符串相关的问题,主要应用有自动补全,拼写检查等。

它的结构很简单啊,放一张图就很清楚了

trie1

代码模版:

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
class Trie:
def __init__(self):
self.children = [None] * 26
self.isEnd = False # 记录是否为一个字符串的尾部

def searchPrefix(self, prefix: str) -> "Trie":
node = self
for ch in prefix:
ch = ord(ch) - ord("a")
if not node.children[ch]:
return None
node = node.children[ch]
return node

def insert(self, word: str) -> None:
node = self
for ch in word:
ch = ord(ch) - ord("a")
if not node.children[ch]:
node.children[ch] = Trie()
node = node.children[ch]
node.isEnd = True

def search(self, word: str) -> bool:
node = self.searchPrefix(word)
return node is not None and node.isEnd

def startsWith(self, prefix: str) -> bool:
return self.searchPrefix(prefix) is not None

代码复制的力扣第208题实现Trie, 还是别人的代码写的漂亮,啊哈哈哈

参考资料

  1. OI wiki