NC124 字典树的实现

描述

字典树又称为前缀树或者Trie树,是处理字符串常用的数据结构。

假设组成所有单词的字符仅是‘a’~‘z’,请实现字典树的结构,并包含以下四个主要的功能。

1. void insert(String word):添加word,可重复添加;
2. void delete(String word):删除word,如果word添加过多次,仅删除一次;
3. boolean search(String word):查询word是否在字典树中出现过(完整的出现过,前缀式不算);
4. 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为前缀的单词数量,其它情况不输出。

数据范围:操作数满足 0≤m≤105,字符串长度都满足 0≤n≤20

进阶:所有操作的时间复杂度都满足 O(n)

示例1

输入:

[["1","qwer"],["1","qwe"],["3","qwer"],["4","q"],["2","qwer"],["3","qwer"],["4","q"]]

返回值:

["YES","2","NO","1"]

备注:

m≤105
∣word∣≤20

Python代码:

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param operators string字符串二维数组 the ops
# @return string字符串一维数组
#


class Trie:
    def __init__(self):
        self.children = dict()
        self.word_num = 0
        self.prefix_num = 0
        
    def insert(self, word):
        node = self
        for char in word:
            if char not in node.children:
                node.children[char] = Trie()
            node.children[char].prefix_num += 1
            node = node.children[char]
        node.word_num += 1
    
    def delete(self, word):
        node = self
        for char in word:
            if char not in node.children:
                return None
            node.children[char].prefix_num -= 1
            node = node.children[char]
        node.word_num -= 1

    def search(self, word):
        node = self
        for char in word:
            if char not in node.children:
                return 0
            node = node.children[char]
        return node.word_num
    
    def prefixNumber(self, pre):
        node = self
        for char in pre:
            if char not in node.children:
                return 0
            node = node.children[char]
        return node.prefix_num


class Solution:
    def trieU(self , operators: List[List[str]]) -> List[str]:
        # write code here
        res = []
        trie = Trie()
        for operator in operators:
            if operator[0] == "1":
                trie.insert(operator[1])
            elif operator[0] == "2":
                trie.delete(operator[1])
            elif operator[0] == "3":
                if trie.search(operator[1]):
                    res.append("YES")
                else:
                    res.append("NO")
            else:
                prefix_num = trie.prefixNumber(operator[1])
                res.append(str(prefix_num))
        return res

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值