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
'코딩테스트 > LeetCode' 카테고리의 다른 글
[LeetCode/Python] 1464. Maximum Product of Two Elements in an Array (0) | 2025.04.10 |
---|---|
[LeetCode/Python] 706. Design HashMap (0) | 2025.04.10 |
[LeetCode/Python] 70. Climbing Stairs (0) | 2025.04.07 |
[LeetCode/Python] 225. Implement Stack using Queues (0) | 2025.04.04 |
[LeetCode/Python] 232. Implement Queue using Stacks (0) | 2025.04.03 |