实现Trie树-Python

# 实现Trie树: 字典套字典
class Trie():
    def __init__(self):
        self.child = {}
    
    def insert(self, word):
        current_node = self.child
        for e in word:
            if e not in current_node:
                current_node[e] = {}
            current_node = current_node[e]
        # 插入单词结束时,给以value为'*'的标志位
        current_node['*'] = '*'
    
    def search(self, word):
        current_node = self.child
        for e in word:
            if e not in current_node:
                return False
            current_node = current_node[e]
            
        return '*' in current_node
    
    def startswith(self, prefix):
        current_node = self.child
        for e in prefix:
            if e not in current_node:
                return False
            current_node = current_node[e]
        return True
    
    
trie = Trie()
trie.insert("apple")
trie.insert("app")
trie.search("ao")
trie.startswith('apllea')

 

posted @ 2022-11-30 16:44  今夜无风  阅读(38)  评论(0编辑  收藏  举报