[LeetCode/Python] 2283. Check if Number Has Equal Digit Count and Digit Value

2025. 4. 9. 21:08

99클럽 코테 스터디 | 비기너 | 8일차


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

 

접근 방법 

1. dictionary를 활용하여 각 인덱스 숫자가 몇 번씩 나타나야 하는지 저장하여 '모범 답안'을 만든다. 예를 들어, 입력 값이 "1210"의 경우 해당하는 dictionary는 {0: 1, 1:2, 2: 1, 3: 0}이 된다.

2. 실제로 각 인덱스 숫자가 몇 번씩 나타났는지 카운트하여 real_count에 저장한다.

3. dictionary에 저장된 인덱스 출현 횟수와 real_count의 횟수를 비교하여 틀릴 경우 false를 return 한다.  

 

class Solution:
    def digitCount(self, num: str) -> bool:
        answer = True
        counter = {}

        # count expected frequency of each digit and set dictionary
        for i in range(len(num)):
            counter.setdefault(i, int(num[i]))

        # count the actual frequency of each digit in num
        for i in range(len(num)):
            real_count = 0

            for j in range(len(num)):
                if i == int(num[j]):
                    real_count += 1
            
            # if expected frequency is different with actual, return false
            if counter[i] != real_count:
                answer = False
                return answer

        return answer

 

 

BELATED ARTICLES

more