eetcode - map sum pairs(kotlin)
level - medium
[문제 내용]
MapSum 클래스를 구현하라.
- void insert(String key, int val), key가 이미 존재하면 덮어쓰기
- int sum(String prefix), prefix로 시작하는 key의 값을 모두 더하여 반환
[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)
[해결 방법]
간결하고 이해하기 쉬운 코드가 좋은 코드 아니겠는가!
간단하게! brute force 방식으로 해결!
class MapSum() {
val mapSum = HashMap<String, Int>()
fun insert(key: String, `val`: Int) {
mapSum[key] = `val`
}
fun sum(prefix: String): Int {
var result = 0
for(key in mapSum.keys) {
if(key.indexOf(prefix) == 0) {
result += mapSum[key]!!
}
}
return result
}
}
Author And Source
이 문제에 관하여(eetcode - map sum pairs(kotlin)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@mdok1112/leetcode-map-sum-pairskotlin저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)