classNode:def__init__(self, c=''):
self.is_end =False
self.subNode =[]
self.c = c
definsert(self, word:str):#构建前缀树next=Nonefor sb in self.subNode:if word[0]== sb.c[0]:next= sb
breakifnotnext:next= Node(word[0])
self.subNode.append(next)iflen(word[1:]):next.insert(word[1:])else:next.is_end =Truedefsearch(self, word:str)->bool:for n in self.subNode:if word[0]=='.'or word[0]== n.c[0]:if word[1:]:
b = n.search(word[1:])if b:# 找到则不再继续returnTrueelse:if n.is_end:returnTrue
classWordDictionary:def__init__(self):"""
Initialize your data structure here.
"""
self.root = Node()defaddWord(self, word:str)->None:"""
Adds a word into the data structure.
"""
self.root.insert(word)defsearch(self, word:str)->bool:"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
res = self.root.search(word)if res:returnTrueelse:returnFalsedefprint_tree(self, node):
vec =[]
vec.append(node)
i =0while i <len(vec):
j =len(vec)
cur_level =[]while i < j:for n in vec[i].subNode:
vec.append(n)
cur_level.append(n.c)
i +=1print(cur_level)