1 class TrieTree(): 2 def __init__(self): 3 self.root = {} 4 5 def addNode(self,str): 6 # 树中每个结点(除根节点),包含到该结点的单词数,以及该结点后面出现字母的键 7 nowdict = self.root 8 for i in range(len(str)): 9 if str[i] not in nowdict: # 发现新的组合方式 10 nowdict[str[i]] = {‘count‘:0,‘prefix‘:str[:i+1]} 11 nowdict = nowdict[str[i]] # 转移到下一个结点 12 nowdict[‘count‘] += 1 13 14 def countWord(self,str): 15 # 返回输入单词在树中出现的次数 16 nowdict = self.root 17 for s in str: 18 if s not in nowdict: 19 return 0 20 nowdict = nowdict[s] # 匹配当前结点,转下一个结点 21 # 到了这一步证明单词存在 22 return nowdict[‘count‘] 23 24 25 26 27 28 if __name__=="__main__": 29 pass 30 Text = [‘b‘,‘abc‘,‘abd‘,‘bcd‘,‘abcd‘,‘efg‘,‘hii‘,‘bcd‘] 31 t = TrieTree() 32 for str in Text: 33 t.addNode(str) 34 print t.countWord(‘bcd‘) 35 36 >>> 2
参考:http://blog.csdn.net/v_july_v/article/details/6897097
时间: 2024-10-12 16:54:20