Trie树的构建、插入、查找操作-python

g功能:快速查找前缀符、字符

class Trie(object):
    def __init__(self):
        self.child = {}
    def insert(self, word):
        current = self.child
        for w in word:
            if w not in current:
                current[w] = {}  # 没有该前缀符,新建一个dict存储
            current = current[w] # 指向下一个深度结构
        current['#'] = 1  # 插入完成后是一个空{},赋予其一个结束标志位
    def search(self, word):
        current = self.child
        for w in word:
            if w not in current:
                return False
            current = current[w]     # 更新
        return '#' in current
    def search_prefix(self, prefix):
        current = self.child
        for w in prefix:
            if w not in current:
                return False
            current = current[w]     # 更新
        return True
t = Trie()
t.insert("deng")

 

posted @ 2022-08-08 14:19  今夜无风  阅读(67)  评论(0编辑  收藏  举报