实现Trie树-Python
# 实现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')
时刻记着自己要成为什么样的人!