2283. 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.
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.
0부터 순서대로 각 정수가 나타난 개수가 num의 각 자리수와 같아야한다.
즉, 위처럼 1210을 받아왔을 때 0의 개수는 1개, 1의 개수는 2개, 2의 개수는 1개, 3의 개수는 0개이어야한다.
이걸 어떻게 구현할지 생각해보면 해시를 사용? - 배열을 사용해서 순회하도록 해야겠다.
< 접근 >
class Solution {
public boolean digitCount(String num) {
//담을 배열
// 반복문1
//문자열로 받은 것 정수형으로 바꾸어서 몇 번 나왔는지 count
//반복문2
//위에서 count한거랑 실제 나온 횟수랑 비교
}
}
< 코드 >
class Solution {
public boolean digitCount(String num) {
int[] count = new int[10];
for(char c : num.toCharArray()){
int digit = c - '0';
count[digit]++;
}
for(int i=0; i<num.length(); i++){
int expect = num.charAt(i) - '0';
if(count[i] != expect){
return false;
}
}
return true;
}
}
- 우선 1210을 받아왔다면 toCharArray를 통해 ['1','2','1','0']이 된다.
- 문자열로 받아온 것을 정수형으로 바꾸는 것이 관건이었는데, '0'의 아스키코드 값은 48이고 '1'의 아스키코드 값은 49이므로 49-48을 하면 1이 나오는 것을 알 수 있다.
- 이렇게 정수로 바꾸고 해당 정수의 개수를 count 한다.
=> count 배열의 최종 상태는 아래와 같다.

- charAt을 통해 i번째 문자를 꺼내고 이전 반복문에서와 마찬가지로 정수형으로 바꿔주고,
count 배열의 해당 번지 숫자와 charAt을 통해 꺼낸 숫자를 차례대로 비교해보면서 일치하면 true를 반환한다.
** 회고
- 배열을 사용해서 접근해야 될 것 같은데 정확히 어떻게 해야할 지 감이 안 잡혔다.
- 문자형을 정수로 바꿀 때 '0'을 이용해서 아스키 코드 번호를 사용한다는 점.
- toCharArray와 charAt의 차이점.
-> 개념 더 공부하자.
'코테 - 자바' 카테고리의 다른 글
| 99클럽 코테 스터디 15일차 TIL + 해시(2) (1) | 2025.04.14 |
|---|---|
| 99클럽 코테 스터디 12일차 TIL + 해시 (1) | 2025.04.11 |
| 99클럽 코테 스터디 6일차 TIL + 수열( (1) | 2025.04.07 |
| 99클럽 코테 스터디 5일차 TIL + 스택/큐(2) (0) | 2025.04.04 |
| 99클럽 코테 스터디 4일차 TIL + 스택/큐 (0) | 2025.04.03 |