python字典树

字典树的节点结构:

class tritree:
    def __init__(self):
        self.dicts={
    
    }
        self.isWord=False

将一个单词加入到字典树,首先我们看这个单词当前字母是否在当前节点的字典中,若不在则生成一个节点,让它对应当前字母,即是将当前字母加入到当前节点的字典中,然后进入下一个节点,若当前字母在当前节点的字典中,则直接进入到下一个节点,当单词遍历完毕,将isWord标记置为True,表示单词存在:

def insert(word, treeNode):
    for s in word:
        if s not in treeNode.dicts:
            treeNode.dicts[s]=tritree()
        treeNode=treeNode.dicts[s]
    treeNode.isWord=True

根据前缀查找单词,如前查找,当前缀中的当前字母不在当前节点的字典中时,说明当前字典树不存在该前缀的单词,直接返回空,若前缀查找完毕,那么对于剩下的部分直接进行dfs即可(dfs写的有点丑陋),一旦遇到isWord为True则加入到列表中:

def dfs(nodes,strs):
    ret=[]
    if nodes.isWord == True:
        ret.append(strs)
    for s,v in nodes.dicts.items():
        tmp=strs
        tmp+=s
        ret.extend(dfs(nodes.dicts[s],tmp))
    return ret

def serch(prefix, treeNode):
    ret, strs = [], ''
    for s in prefix:
        if s not in treeNode.dicts:
            return []
        strs += s
        treeNode = treeNode.dicts[s]
    ret=dfs(treeNode, strs)
    return ret

运行效果:

obj=tritree()
insert("apple",obj)
insert("app",obj)
print(serch("aps",obj))      #[]
insert("appppppple",obj)
print(serch("ap",obj))       #['app', 'apple', 'appppppple']

рекомендация

отblog.csdn.net/qq_45782128/article/details/121325167