Input: num ="1210"Output: trueExplanation:
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 truefor every index in"1210", so returntrue.
Input: num ="030"Output: falseExplanation:
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 returnfalse.
By counting the frequency of each digit in the string, we can directly compare the count of digit i with the value at num[i] for all indices. If all match, the condition is satisfied.
classSolution {
publicbooleandigitCount(String num) {
int[] cnt =newint[10];
for (char c : num.toCharArray()) cnt[c -'0']++;
for (int i = 0; i < num.length(); i++) {
if (cnt[i]!= num.charAt(i) -'0') returnfalse;
}
returntrue;
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
fundigitCount(num: String): Boolean {
val cnt = IntArray(10)
for (c in num) cnt[c - '0']++for (i in num.indices) {
if (cnt[i] != num[i] - '0') returnfalse }
returntrue }
}
1
2
3
4
5
6
7
8
9
classSolution:
defdigit_count(self, num: str) -> bool:
cnt = [0] *10for c in num:
cnt[int(c)] +=1for i, ch in enumerate(num):
if cnt[i] != int(ch):
returnFalsereturnTrue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfndigit_count(num: String) -> bool {
letmut cnt = [0; 10];
for c in num.chars() {
cnt[c asusize-'0'asusize] +=1;
}
for (i, ch) in num.chars().enumerate() {
if cnt[i] != ch asusize-'0'asusize {
returnfalse;
}
}
true }
}