一种字典树的Python实现

字典树,也叫单词查找树,Trie, 是一种自定义的树形数据结构,用于统计、排序和保存大量的字符串,利用字符串的公共前缀来减少查询时间和存储空间,查找效率比哈希树高。
字典树应该支持的操作:插入 查找 前缀 移除 展示:
insert(word): Insert a word into the Trie
search(word): Return if the word in the Trie
startsWith(prefix): Return if there is any words in the trie that starts with the given prefix
remove(word): Remove word from the Trie
show(): Print the architecture of the Trie using indents

Python实现

class Trie:
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.dic = {}

    def insert(self, word: str) -> None:
        """
        Inserts a word into the trie.
        """
        tree = self.dic
        for i in word:
            tree = tree.setdefault(i, {})
        tree['#'] = '#'

    def search(self, word: str) -> bool:
        """
        Returns if the word is in the trie.
        """
        tree = self.dic
        for i in word:
            if i not in tree:
                return False
            tree = tree[i]
        return '#' in tree

    def startsWith(self, prefix: str) -> bool:
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """
        tree = self.dic
        for i in prefix:
            if i not in tree:
                return False
            tree = tree[i]
        return True
    
    def remove(self, word: str) -> None:
        """
        Remove the word from the Trie.
        """
        def _remove_helper(node, word, index):
            if index == len(word):
                # 找到单词末尾,删除结束标记
                if '#' in node:
                    del node['#']
                return len(node) == 0  # 如果节点没有其他子节点,可以删除
                
            char = word[index]
            if char not in node:
                return False  # 单词不存在
            
            should_delete = _remove_helper(node[char], word, index + 1)
            
            if should_delete:
                del node[char]
            return len(node) == 0  # 检查当前节点是否可以删除
            
        _remove_helper(self.dic, word, 0)
    
    def show(self):
        """
        以缩进形式层次化展示Trie树结构
        """
        def _show_helper(node, level=0):
            for key, child in node.items():
                if key == '#':
                    print('  ' * level + '# (end)')
                else:
                    print('  ' * level + key)
                    _show_helper(child, level + 1)
        
        _show_helper(self.dic)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值