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/description/
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.
Example 1:
Input: num = "1210"
Output: true
Explanation:
num[0] = '1'. The digit 0 occurs once in num.
num[1] = '2'. The digit 1 occurs twice in num.
num[2] = '1'. The digit 2 occurs once in num.
num[3] = '0'. The digit 3 occurs zero times in num.
The condition holds true for every index in "1210", so return true.
Example 2:
Input: num = "030"
Output: false
Explanation:
num[0] = '0'. The digit 0 should occur zero times, but actually occurs twice in num.
num[1] = '3'. The digit 1 should occur three times, but actually occurs zero times in num.
num[2] = '0'. The digit 2 occurs zero times in num.
The indices 0 and 1 both violate the condition, so return false.
Constraints:
n == num.length
1 <= n <= 10
num consists of digits.
한글 해석
문제 유형
Hash Table
String
Counting
풀이 방법 도출
문자열 num이 주어졌을 때, 각 인덱스 i에 있는 문자가 나타내는 숫자가 해당 숫자(i)가 문자열 num에 등장한 횟수와 같은지 확인합니다.
예시:
num = "1210"
- 인덱스 0의 문자는 '1' → 숫자 1이 총 1번 등장
- 인덱스 1의 문자는 '2' → 숫자 1이 총 2번 등장
- 인덱스 2의 문자는 '1' → 숫자 2가 총 1번 등장
- 인덱스 3의 문자는 '0' → 숫자 3이 총 0번 등장
=> 모두 조건을 만족하므로 true를 반환
시간 복잡도
- O(N)
핵심 코드 삽입 및 설명
public class Solution {
public boolean digitCount(String num) {
// 0부터 9까지 각 숫자의 등장 횟수를 저장할 배열
int[] count = new int[10];
// 각 숫자의 등장 횟수 세기
for (int i = 0; i < num.length(); i++) {
// 문자 '0'~'9'를 숫자로 변환해서 count 배열 증가
count[num.charAt(i) - '0']++;
}
// 각 인덱스에 해당하는 숫자의 등장 횟수와 값 비교
for (int i = 0; i < num.length(); i++) {
// 해당 인덱스에 요구되는 등장 횟수
int expectedCount = num.charAt(i) - '0';
if (count[i] != expectedCount) {
return false; // 조건을 만족하지 않으면 false 반환
}
}
return true; // 모든 조건을 만족하면 true 반환
}
}
'Study > 코딩 테스트' 카테고리의 다른 글
[백준] 1436번 영화감독 숌 해설 및 풀이 (Python) (0) | 2025.04.10 |
---|---|
[LeetCode] LeetCode 1679. Max Number of K-Sum Pairs 해설 및 풀이 (Python) (0) | 2025.04.10 |
[프로그래머스] Lv.1 같은 숫자는 싫어 해설 및 풀이 (Python) (0) | 2025.04.09 |
[LeetCode] 1493. Longest Subarray of 1's After Deleting One Element 해설 및 풀이 (Python) (0) | 2025.04.09 |
[LeetCode] 11. Container With Most Water 해설 및 풀이 (Python) (0) | 2025.04.08 |