class MapSum {
public:
/** Initialize your data structure here. */
MapSum() {
m_.clear();
}
void insert(string key, int val) {
m_[key] = val;
}
int sum(string prefix) {
int ans = 0;
int size = prefix.size();
for (auto p : m_) {
if (p.first.size() < size) continue;
int i = 0;
for (; i < size; ++i)
if (p.first[i] != prefix[i]) break;
if (i == size)
ans += p.second;
}
return ans;
}
private:
map<string, int> m_;
};
/** Initialize your data structure here. */
MapSum() {
score.clear();
m.clear();
}
void insert(string key, int val) {
int delta = m[key];
m[key] = val;
string k = "";
for (int i = 0; i < key.size(); ++i) {
k += key[i];
score[k] += val - delta;
}
}
int sum(string prefix) {
return score[prefix];
}
private:
map<string, int> score;
map<string, int> m;
};
'알고리즘 > leetcode' 카테고리의 다른 글
Two Sum - easy (0) | 2021.08.02 |
---|---|
Making A Large Island (0) | 2021.08.01 |
Partition Array into Disjoint Intervals (0) | 2021.07.22 |
Push Dominoes (0) | 2021.07.22 |
leetcode - Find the Town Judge - easy (0) | 2020.09.22 |