# 实现Trie树: 字典套字典 class Trie(): def __init__(self): self.child = {} def insert(self, word): current_node = self.child for e in word: if e not in current_node: current_node[e] = {} current_node = current_node[e] # 插入单词结束时,给以value为'*'的标志位 current_node['*'] = '*' def search(self, word): current_node = self.child for e in word: if e not in current_node: return False current_node = current_node[e] return '*' in current_node def startswith(self, prefix): current_node = self.child for e in prefix: if e not in current_node: return False current_node = current_node[e] return True trie = Trie() trie.insert("apple") trie.insert("app") trie.search("ao") trie.startswith('apllea')
标签:node,return,Trie,self,current,Python,trie,实现 From: https://www.cnblogs.com/demo-deng/p/16938982.html