😎풀이

  1. Map 객체를 활용해 key-value 형태로 insert 덮어쓰기
  2. Map 내부를 순회하며, 접두사로 prefix가 붙은 경우 합산 및 반환
class MapSum {
    private map: Map<string, number>
    constructor() {
        this.map = new Map<string, number>()
    }

    insert(key: string, val: number): void {
        this.map.set(key, val)
    }

    sum(prefix: string): number {
        let total = 0
        for(const [key, val] of this.map) {
            if(!key.startsWith(prefix)) continue
            total += val
        }
        return total
    }
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글