python简介版

字典树的实现

http://www.nowcoder.com/questionTerminal/a55a584bc0ca4a83a272680174be113b

1. 稍微复杂一点的是求前缀串的数量,这里用dfs计算以当前节点为跟的字典树中包含的所有‘#’的数量,即完整的字符串个数
2. 还需要思考的就是删除字符串,这里查找以字符串结尾的字典删掉即可
3. 这道题比LeetCode[208. 实现 Trie (前缀树)]难很多,大家可以自行练习秒掉它

class Tree:
    def __init__(self):
        self.tree = {}

    def insert(self, word):
        cur = self.tree
        for w in word:
            if w not in cur:
                cur[w] = {}
            cur = cur[w]
        cur['#'] = 1

    def delete(self, word):
        cur = self.tree
        for w in word:
            if word[-1] in cur:
                del cur[word[-1]]
                break
            cur = cur[w]

    def search(self, word):
        cur = self.tree
        for w in word:
            if w not in cur:
                return 'NO'
            cur = cur[w]
        return 'YES' if '#' in cur else 'NO'

    def dfs(self, cur):
        ans = int('#' in cur)
        for k, v in cur.items():
            if type(v) == dict:
                ans += self.dfs(v)
        return ans

    def prefixNumber(self, pre):
        cur = self.tree
        for w in pre:
            if w not in cur:
                return 0
            cur = cur[w]
        return self.dfs(cur)


class Solution:

    def trieU(self, operators):
        # write code here
        ans = []
        obj = Tree()
        for op, word in operators:

            if op == '1':
                obj.insert(word)
            elif op == '2':
                obj.delete(word)
            elif op == '3':
                ans.append(obj.search(word))
            else:
                ans.append(obj.prefixNumber(word))
        return ans
全部评论
兄弟,答案用例第二个就过不去了
1 回复 分享
发布于 2022-06-09 16:54

相关推荐

11-24 11:23
门头沟学院 C++
点赞 评论 收藏
分享
过往烟沉:我说什么来着,java就业面就是广!
点赞 评论 收藏
分享
评论
5
收藏
分享
牛客网
牛客企业服务