def__init__(self): """ Initialize your data structure here. """ self.root = {} self.end_of_word = '#'
definsert(self, word: str) -> None: """ Inserts a word into the trie. """ node = self.root for char in word: node = node.setdefault(char, {}) node[self.end_of_word] = self.end_of_word
defsearch(self, word: str) -> bool: """ Returns if the word is in the trie. """ node = self.root for char in word: if char notin node: returnFalse node = node[char] return self.end_of_word in node
defstartsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ node = self.root for char in prefix: if char notin node: returnFalse node = node[char] returnTrue
defget_start(self,prefix): ''' 给出一个前辍,打印出所有匹配的字符串 :param prefix: :return: ''' defget_key(pre,pre_node): result = [] if pre_node.get(self.end_of_word): result.append(pre) for key in pre_node.keys(): if key != self.end_of_word: result.extend(get_key(pre+key,pre_node.get(key))) return result
ifnot self.startsWith(prefix): return [] else: node = self.root for p in prefix: node = node.get(p) else: return get_key(prefix,node)