LeetCode 677. 键值映射

本文介绍了两种方法实现MapSum类,一种是利用Python和Java中的字典以及字符串的startswith方法,另一种是通过字典树(Trie树)来优化查找效率。这两种方法分别详细地展示了类的定义、插入操作和前缀求和功能。
摘要由CSDN通过智能技术生成

题目链接: 

力扣https://leetcode-cn.com/problems/map-sum-pairs/

【方法一】直接用python或者java中的字典和字符串的startswith方法

class MapSum:
    def __init__(self):
        self.map = {}
    def insert(self, key: str, val: int) -> None:
        self.map[key] = val
    def sum(self, prefix: str) -> int:
        ans = 0
        for k in self.map.keys():
            if k.startswith(prefix):
                ans += 1
        return ans
class MapSum {

        public HashMap<String, Integer> hashMap;

        public MapSum() {
            hashMap = new HashMap<>();
        }

        public void insert(String key, int val) {
            hashMap.put(key, val);
        }

        public int sum(String prefix) {
            int ans = 0;
            for(Map.Entry<String, Integer> entry: hashMap.entrySet()){
                if(entry.getKey().startsWith(prefix)) ans += entry.getValue();
            }
            return ans;
        }
    }

 

 【方法二】字典树

class MapSum {
    public int value;
    public boolean is_end;
    public Map<Character, MapSum> map = new HashMap<>();

    /** Initialize your data structure here. */
    public MapSum() {

    }

    public void insert(String key, int val) {
        MapSum cur = this;
        int n = key.length(), i;
        char c;
        for(i = 0; i < n; i++){
            c = key.charAt(i);
            if(cur.map.containsKey(c)) cur = cur.map.get(c);
            else{
                cur.map.put(c, new MapSum());
                cur = cur.map.get(c);
            }
        }
        cur.value = val;
        cur.is_end = true;
    }

    public int dfs(MapSum node){
        int ret = 0;
        if(node.is_end) ret += node.value;
        for(Map.Entry<Character, MapSum> entry: node.map.entrySet()){
            ret += dfs(entry.getValue());
        }
        return ret;
    }

    public int sum(String prefix) {
        int n = prefix.length(), i;
        char c;
        MapSum cur = this;
        for(i = 0; i < n; i++) {
            c = prefix.charAt(i);
            if(cur.map.containsKey(c)) cur = cur.map.get(c);
            else return 0;
        }
        return dfs(cur);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值