前缀树可以用来解决诸如搜索提示,字符串查询等问题,实现一个前缀树首先需要定义一个前缀树结点,结点不代表字符串中的字符,每个结点的值通常有end(表示是否是某个字符串结尾),past(表示有多少单词经过此结点),next_node(是一个字典,其中key代表此结点相连的字符,value代表这条字符所代表的边连接的结点)。
定义前缀树类时,首先要初始化一个前缀树结点,然后定义常用的方法,如插入,删除,搜索和startwith,其基本搜索过程类似,以插入举例,首先定义一个变量node指向root,然后循环遍历字符串,若next_node[当前遍历字符]为空,说明没有当前字符的边,我们直接将这个key加入哈希表,下一步将node更新至next_node[当前遍历字符],当遍历完成后,说明遍历到了字符串末尾,定义node.end = True(若想下次查询获取加入次数,则这里应当定义为数字)
class Trienode:
def __init__(self):
self.end = False
self.next_node = {}
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = Trienode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
if not word:
return
node = self.root
for w in word:
if w not in node.next_node:
node.next_node[w] = Trienode()
node = node.next_node[w]
node.end = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
if not word:
return False
node = self.root
for w in word:
if w not in node.next_node:
return False
node = node.next_node[w]
return node.end
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
node = self.root
for w in prefix:
if w not in node.next_node:
return False
node = node.next_node[w]
return True