Trie 前缀树 Python实现

题目描述

字典树又称为前缀树或者Trie树,是处理字符串常用的数据结构。假设组成所有单词的字符仅是‘a’~‘z’,请实现字典树的结构,并包含以下四个主要的功能。void insert(String word):添加word,可重复添加;void delete(String word):删除word,如果word添加过多次,仅删除一次;boolean search(String word):查询word是否在字典树中出现过(完整的出现过,前缀式不算);int prefixNumber(String pre):返回以字符串pre作为前缀的单词数量。现在给定一个m,表示有m次操作,每次操作都为以上四种操作之一。每次操作会给定一个整数op和一个字符串word,op代表一个操作码,如果op为1,则代表添加word,op为2则代表删除word,op为3则代表查询word是否在字典树中,op为4代表返回以word为前缀的单词数量(数据保证不会删除不存在的word)。

对于每次操作,如果op为3时,如果word在字典树中,请输出“YES”,否则输出“NO”;如果op为4时,请输出返回以word为前缀的单词数量,其它情况不输出。

输入: [[“1”,“qwer”],[“1”,“qwe”],[“3”,“qwer”],[“4”,“q”],[“2”,“qwer”],[“3”,“qwer”],[“4”,“q”]]

返回值:[“YES”,“2”,“NO”,“1”]

代码

class Trie: 
    def __init__(self):
        self.root = {} # 使用dict代替树结构
        
    def insert(self, word):
        if len(word) > 0:
            cur = self.root
            for c in word:
                if c not in cur:
                    cur[c] = {}
                cur = cur[c]
            cur['#'] = True
    
    def delete(self, word):
        if len(word) > 0 and self.find(word):
            stack = []
            cur = self.root
            is_end = True
            for c in word:
                stack.append(cur) # 不要写成append(cur[c]),我们添加的是从root到倒数第二个节点
                cur = cur[c]
                
            if len(cur) > 1: #判断这个单词是不是最后的词,即不是其他单词的前缀
                is_end = False
                
            for i, c in enumerate(word[::-1]):
                parent = stack.pop()
                if is_end == False: # 注意parent和parent[c]的区别
                    parent[c].pop('#')
                    break
                elif '#' in parent[c] and i == 0: 
                    parent.pop(c)
                elif len(parent[c]) == 0: # 只有当这条路径中只有这个词的时候,才能删掉这个字母
                    parent.pop(c)
                
               
            
            
    def search(self, word):
        if self.find(word):
            return 'Yes'
        else:
            return 'No'
        
    def find(self, word):
        if len(word) > 0:
            cur = self.root
            for c in word:
                if c not in cur:
                    return False
                cur = cur[c]
            if '#' in cur:
                return True
        
        return False
    
    def prefixNumber(self, pre):
        cur = self.root
        for c in pre:
            if c not in cur:
                return 0
            cur = cur[c]
        
        return self.countPaths(cur)
    
    def countPaths(self, cur):     
        if len(cur) == 1 and '#' in cur:
            return 1
        
        count = 0
        for c in cur:
            if c == '#':
                count += 1
                continue
            count += self.countPaths(cur[c]) #不要写成self.countPaths(c), c只是一个key,我们要传的是值
            
        return count
        

trie = Trie()
trie.insert('ap')
trie.insert('app')
trie.insert('apd')
trie.insert('appb')
print(trie.prefixNumber('ap'))
trie.delete('appb')
print(trie.search('ap'))
print(trie.search('app'))
print(trie.search('apd'))
print(trie.search('appb'))
print(trie.prefixNumber('ap'))

运行结果

4
Yes
Yes
Yes
No
3
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值