字典树-208. 实现 Trie (前缀树)-PYTHON
python利用字典结构的简便版本(注意看注释理解) class Trie : def __init__ ( self ) : """ Initialize your data structure here. """ self . lookup = { } #构建一个字典结构,用于存储元素数据 def insert ( self , word ) : """ Inserts a word into the trie. """ tree = self . lookup #给公共字典取别名 for a in word : if a not in tree : tree [ a ] = { } #逐元素提取字母到字典中查找是否存在,如果不存在就在字典内建立一个空的子字典 tree = tree [ a ] #跟踪标记位置变换,进入到字字典中进行操作 # 单词结束标志 tree [ "#" ] = "#" #插入单词结束在最后一个字字典中插入结束符 print ( self . lookup ) def search ( self , word ) : """ Returns if the word is in the trie. """ tree = self . lookup for a in word : if a not in tree : #{u'a': {u'p': {u'p'