字典树

作者: lizg | 来源:发表于2022-05-11 19:34 被阅读0次

    字典树的python实现

    # coding:utf-8
    
    class Trie(object):
        """字典树的删改查"""
        def __init__(self):
            self.lookup = {}
    
        def insert(self, word: str) -> None:
            tree = self.lookup
            for a in word:
                if a not in tree:
                    tree[a] = {}
                tree = tree[a]
            tree['#'] = '#'
    
        def search(self, word: str) -> bool:
            tree = self.lookup
            for a in word:
                if a not in tree:
                    return False
                tree = tree[a]
            if '#' in tree:
                return True
            return False
    
        def startsWith(self, prefix: str) -> bool:
            tree = self.lookup
            for a in prefix:
                if a not in tree:
                    return False
                tree = tree[a]
            return True
        @property
        def content(self):
            return self.lookup
    
    
    if __name__ == '__main__':
        trie = Trie()
        trie.insert("你好吗")
        trie.insert("我好呀")
        trie.insert("你好吗,我是新来的")
        print(trie.content)
        print(trie.search("你好吗"))
        print(trie.startsWith("我是"))
        print(trie.startsWith("你"))
    
    
    
    trie.PNG

    相关文章

      网友评论

          本文标题:字典树

          本文链接:https://www.haomeiwen.com/subject/lukjurtx.html