Skip to content

Latest commit

 

History

History
193 lines (152 loc) · 4.54 KB

File metadata and controls

193 lines (152 loc) · 4.54 KB

中文文档

Description

Design a map that allows you to do the following:

  • Maps a string key to a given value.
  • Returns the sum of the values that have a key with a prefix equal to a given string.

Implement the MapSum class:

  • MapSum() Initializes the MapSum object.
  • void insert(String key, int val) Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new one.
  • int sum(string prefix) Returns the sum of all the pairs' value whose key starts with the prefix.

 

Example 1:

Input
["MapSum", "insert", "sum", "insert", "sum"]
[[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
Output
[null, null, 3, null, 5]

Explanation
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)

 

Constraints:

  • 1 <= key.length, prefix.length <= 50
  • key and prefix consist of only lowercase English letters.
  • 1 <= val <= 1000
  • At most 50 calls will be made to insert and sum.

Solutions

Python3

class MapSum:
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.data = defaultdict(int)
        self.t = defaultdict(int)

    def insert(self, key: str, val: int) -> None:
        old = self.t[key]
        self.t[key] = val
        for i in range(1, len(key) + 1):
            self.data[key[:i]] += val - old

    def sum(self, prefix: str) -> int:
        return self.data[prefix]


# Your MapSum object will be instantiated and called as such:
# obj = MapSum()
# obj.insert(key,val)
# param_2 = obj.sum(prefix)

Java

class MapSum {
    private Map<String, Integer> data;
    private Map<String, Integer> t;

    /** Initialize your data structure here. */
    public MapSum() {
        data = new HashMap<>();
        t = new HashMap<>();
    }

    public void insert(String key, int val) {
        int old = t.getOrDefault(key, 0);
        t.put(key, val);
        for (int i = 1; i < key.length() + 1; ++i) {
            String k = key.substring(0, i);
            data.put(k, data.getOrDefault(k, 0) + (val - old));
        }
    }

    public int sum(String prefix) {
        return data.getOrDefault(prefix, 0);
    }
}

/**
 * Your MapSum object will be instantiated and called as such:
 * MapSum obj = new MapSum();
 * obj.insert(key,val);
 * int param_2 = obj.sum(prefix);
 */

C++

class MapSum {
public:
    unordered_map<string, int> data;
    unordered_map<string, int> t;

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

    void insert(string key, int val) {
        int old = t[key];
        t[key] = val;
        for (int i = 1; i < key.size() + 1; ++i) {
            string k = key.substr(0, i);
            data[k] += (val - old);
        }
    }

    int sum(string prefix) {
        return data[prefix];
    }
};

/**
 * Your MapSum object will be instantiated and called as such:
 * MapSum* obj = new MapSum();
 * obj->insert(key,val);
 * int param_2 = obj->sum(prefix);
 */

Go

type MapSum struct {
	data map[string]int
	t    map[string]int
}

/** Initialize your data structure here. */
func Constructor() MapSum {
	return MapSum{
		data: make(map[string]int),
		t:    make(map[string]int),
	}
}

func (this *MapSum) Insert(key string, val int) {
	old := this.t[key]
	this.t[key] = val
	for i := 1; i < len(key)+1; i++ {
		k := key[:i]
		this.data[k] += (val - old)
	}
}

func (this *MapSum) Sum(prefix string) int {
	return this.data[prefix]
}

/**
 * Your MapSum object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Insert(key,val);
 * param_2 := obj.Sum(prefix);
 */

...