leetcode - map sum pairs(kotlin)

silver·2021년 7월 31일
0

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
    }
}

0개의 댓글