class Trie:
def __init__(self):
self.root = dict()
self.end = "$"
def insert(self, item: str):
node = self.root
for char in item:
node = node.setdefault(char, {
}) # 有值 return值; 無值設值並 return值
node[self.end] = self.end
def __collection(self, node):
if node == self.end:
return [""]
res = []
for i in node:
the = node[i]
remain = self.__collection(the)
for j in remain:
res.append(i + j)
return res
def __getitem__(self, item: str):
node = self.root
for char in item:
if char not in node:
return []
node = node[char]
output = self.__collection(node)
for i in range(len(output)):
output[i] = (item + output[i])[:-1]
return output
def reset(self):
self.root.clear()