본문 바로가기
99클럽 코테 스터디

[99클럽 코테 스터디 8일차 TIL] Check if Number Has Equal Digit Count and Digit Value

by sozr 2025. 4. 9.

 

 

오늘의 키워드

  • 해시맵

 

leetcode 2283번: Check if Number Has Equal Digit Count and Digit Value

https://leetcode.com/problems/check-if-number-has-equal-digit-count-and-digit-value/

 

 

문제

 

You are given a 0-indexed string num of length n consisting of digits.
Return true if for every index i in the range 0 <= i < n, the digit i occurs num[i] times in num, otherwise return false.

 

 

input이 '1210' 이라면

num[0] = '1' 0이 하나 있으므로 true

num[1] = '2' 1가 두개 있으므로 true

num[2] = '1' 2가 하나 있으므로 true

num[3] = '0' 3이 없으므로 true 

 

입력예제

1210
030

 

 

 

출력예제

true
false

 

풀이

 

 해시맵을 사용해서 풀어보았다.

1. 우선 해시맵에 특정 숫자가 몇번들어가 있는지 넣는다 key값은 특정 숫자, value는 몇번 들어갔는지 횟수를 넣는다.

2. 한번 더 문자를 돌면서 각 인덱스의 횟수를 hash에서 찾아서 비교 후 다르다면 false를 같다면 true를 출력한다.

 

 

class Solution {
    public boolean digitCount(String num) {
        boolean result = true;
        HashMap<Integer, Integer> hash = new HashMap<>();

        for(int i=0; i<num.length(); i++){
            int v = num.charAt(i) -'0'; 
            hash.put(v, hash.getOrDefault(v,0)+1);
        }

        for(int i=0; i<num.length(); i++){
            int expect = hash.getOrDefault(i, 0);       // 기댓값
            int real = num.charAt(i) -'0';              // 실제값

            if(expect != real) result = false;
        }



        return result;
    }
}

 

 

 

코드를 돌려보니 제출한 사용자들보다 속도가 느리게 나와서

배열로도 다시 풀어보았다.

 

 

class Solution {
    public boolean digitCount(String num){
        int count[] = new int[10]; // 0~9

        for(int i=0; i<num.length(); i++){
            int x = num.charAt(i) - '0';
            count[x]++;
        }

        for(int i=0; i<num.length(); i++){
            int y = num.charAt(i) - '0';
            if(count[i] != y) return false;
        }

        return true;
    }

}

 

 

 

숫자는 0부터 9까지이므로 배열을 사용해서 공간을 줄였더니 2ms -> 0ms로 바뀌었다