Python实现Tire树

class Project(object):
    def __init__(self):
        self.node = {}
        self.end_char = '#'
    def insert(self, word):
        node = self.node
        for char in word:
            node = node.setdefault(char, {})
        node[self.end_char] = self.end_char
    def search(self, word):
        node = self.node
        for char in word:
            if char not in node:
                return False
            node = node[char]
        return self.end_char in node
    def startWith(self, prefix):
        node = self.node
        for char in prefix:
            if char not in node:
                return False
            node = node[char]
        return True

if __name__ == '__main__':
    t = Project()
    t.insert('xuexi')
    t.insert('duexi')
    t.insert('xia')
    print(t.search('xuexi'))
    print(t.startWith('zhao'))

 

posted @ 2021-05-25 20:11  今夜无风  阅读(157)  评论(0编辑  收藏  举报