
解題思路:
這道題可以開掛一波,反向套娃,你讓我實作鍵值映射,那我就用鍵值映射實作,直接定義一個map,用來記錄string和int對,sum函式實作時,通過substr來統計擁有prefix的值的和,代碼如下:
class MapSum {
private:
unordered_map<string, int> mp;
public:
MapSum() {
}
void insert(string key, int val) {
mp[key] = val;
}
int sum(string prefix) {
int count = 0;
for(auto& [k, v] : mp) {
if(k.substr(0, prefix.size()) == prefix) {
count += v;
}
}
return count;
}
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum* obj = new MapSum();
* obj->insert(key,val);
* int param_2 = obj->sum(prefix);
*/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/357034.html
標籤:其他
上一篇:備戰藍橋杯——演算法訓練之過河馬
