字典树的添加,删除以及查找,数量统计
#!/usr/bin/python
#coding: utf-8
class TrieNode(object):
def __init__(self):
self.is_word = False # 判断是否是单词
self.children = [None] * 256
class Trie(object):
def __init__(self, ):
self.root = TrieNode()
# 统计当前的单词数量
self.count = 0
def Add(self, s):
"Add a string to this trie."
n = len(s)
p = self.root
for i in range(n):
if p.children[ord(s[i])] is None:
new_node = TrieNode()
if i == n - 1:
new_node.is_word = True
self.count += 1
p.children[ord(s[i])] = new_node
p = new_node
else:
p = p.children[ord(s[i])]
if i == n - 1:
p.is_word = True
self.count += 1
return
def Search(self, s):
"Search the word in this trie."
p = self.root
for c in s:
p = p.children[ord(c)]
if p is None:
return False
if p.is_word == False:
return False
return True
"""
删除单词的时候,只能修改 is_word 的值,不能修改存储的对应节点,
因为判断是否是单词的时候,只是通过 is_word 的值进行判断。
举例如下:字典树中存在两个单词:child children
再删除child的时候,要保证不能影响children。
"""
def Delete(self, s):
"Delete the word in this trie."
p = self.root
for c in s:
p = p.children[ord(c)]
if p is None:
return u"当前单词不存在!"
if p.is_word == False:
return u"当前单词不存在!"
p.is_word = False
self.count -= 1
return u"删除成功"
def Get_Count(self):
return self.count
if __name__ == "__main__":
trie = Trie()
trie.Add('str')
trie.Add('acb')
trie.Add('acblde')
trie.Add('I like Python!')
print trie.Search('acb')
print trie.Search('ac')
trie.Add('ac')
print u"当前单词的数量为:%d" % trie.Get_Count()
print trie.Search('ac')
print trie.Search("I like Python!")
print trie.Search("a")
print trie.Delete("ac")
print trie.Search("ac")
print u"当前单词的数量为:%d" % trie.Get_Count()