一个prefix tree是存储字符串的数据结构,他每一个节点有无数个子节点,每一个节点表示一个字母。
从子节点走到相应的结尾节点,经过的字母连接起来就是相应的字符串.
在定义数据结构的时候,我们首先定义ListNode:
class ListNode:
def __init__(self, val, flag):
self.val = val
self.child = {} # a map that stores all the child nodes
self.flag = flag
我们使用一个map来存储当前节点的子节点,同时我们用一个flag来记录当前节点是不是一个字符串的结束节点。
考虑:当我们输入一个“apple”了之后,我们仍可以顺着trie寻找到“app”,但是app并不是我们插入的一个字符串,所以我们通过看flag来判断当前节点是不是一个字符串的结尾。
class ListNode:
def __init__(self, val, flag):
self.val = val
self.child = {} # a map that stores all the child nodes
self.flag = flag
class Trie:
def __init__(self):
self.root = ListNode("",0)
def insert(self, word: str) -> None:
temp = self.root # get the pointer to iterate
for char in word:# we only have to compare n steps
if temp.child.get(char) != None:
temp = temp.child[char]
else:
new = ListNode(char, 0)
temp.child[char] = new
temp = new
temp.flag = 1
def search(self, word: str) -> bool:
temp = self.root
for char in word:
if temp.child.get(char) == None:
return False
else:
temp = temp.child[char]
if temp.flag == 1:
return True
else:
return False
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
temp = self.root
for char in prefix:
if temp.child.get(char) == None:
return False
else:
temp = temp.child[char]
return True