zoukankan      html  css  js  c++  java
  • 677. 键值映射

    实现一个 MapSum 类,支持两个方法,insert 和 sum:

    MapSum() 初始化 MapSum 对象
    void insert(String key, int val) 插入 key-val 键值对,字符串表示键 key ,整数表示值 val 。如果键 key 已经存在,那么原来的键值对将被替代成新的键值对。
    int sum(string prefix) 返回所有以该前缀 prefix 开头的键 key 的值的总和。
     

    示例:

    输入:
    ["MapSum", "insert", "sum", "insert", "sum"]
    [[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
    输出:
    [null, null, 3, null, 5]

    解释:
    MapSum mapSum = new MapSum();
    mapSum.insert("apple", 3);
    mapSum.sum("ap"); // return 3 (apple = 3)
    mapSum.insert("app", 2);
    mapSum.sum("ap"); // return 5 (apple + app = 3 + 2 = 5)
     

    提示:

    1 <= key.length, prefix.length <= 50
    key 和 prefix 仅由小写英文字母组成
    1 <= val <= 1000
    最多调用 50 次 insert 和 sum

    class MapSum:
    
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.dict={}
    
    
        def insert(self, key: str, val: int) -> None:
            self.dict[key]=val
    
        def sum(self, prefix: str) -> int:
            res=0
            for i in self.dict:
                if i.startswith(prefix):
                    res+=self.dict[i]
            return res
    
    
    
    # Your MapSum object will be instantiated and called as such:
    # obj = MapSum()
    # obj.insert(key,val)
    # param_2 = obj.sum(prefix)
  • 相关阅读:
    C语言I博客作业02
    第一次C语言作业
    C语言I博客作业02
    网页常用分享代码
    js生成验证码并验证
    js时间格式的转换
    Git 常用命令
    ASP.NET MVC中使用事务写法
    数据库游标导入数据
    js截取所需字符串长度
  • 原文地址:https://www.cnblogs.com/xxxsans/p/14008113.html
Copyright © 2011-2022 走看看