前缀树实现,遍历字符串。把字符串中的每一个字符都视为前缀,用一个前缀树保存以每一个字符为开头的字符串(举例为‘abbc’)。然后遍历前缀树,把每个子树的每一层都作为一个字符串输出即可。
import copy
class TrieNode(object):
def __init__(self,word):
self.word = word
self.dict1 = {}
str1 = 'abbc'
str1 = list(str1)
root = TrieNode(None)
def buildtree(root,word):
if word not in root.dict1:
obj = TrieNode(word)
root.dict1[word]=obj
else:
obj = root.dict1[word]
return obj
def findword(root,list1):
if root.dict1:
if root.word:
list1.append(root.word)
lenth = len(list1)
for key in root.dict1:
findword(root.dict1[key],list1)
del list1[lenth:]
if len(list1)>0:
temp = copy.copy(list1)
res.append(''.join(temp))
else:
list1.append(root.word)
temp = copy.copy(list1)
res.append(''.join(temp))
res = []
for i in range(len(str1)):
head = root
for j in range(i,len(str1)):
head = buildtree(head,str1[j])
findword(root,[])
print(res)