判断一个数的数字计数是否等于数位的值【LC2283】
You are given a 0-indexed string
num
of lengthn
consisting of digits.Return
true
if for every indexi
in the range0 <= i < n
, the digiti
occursnum[i]
times innum
, otherwise returnfalse
.
-
思路:使用哈希表统计每个数字出现的次数,再与字符串中的次数进行比较,如果所有数字次数均等于字符串中的次数,返回
true
;反之,返回false
-
实现
class Solution { public boolean digitCount(String num) { int[] count = new int[10]; for (int i = 0; i < num.length(); i++){ count[num.charAt(i) - '0']++; } for(int i = 0; i < num.length(); i++){ if (count[i] != num.charAt(i) - '0'){ return false; } } return true; } }
- 复杂度
- 时间复杂度: O ( n ) O(n) O(n),n为字符串长度
- 空间复杂度: O ( C ) O(C) O(C),C为字符集大小,本题中为10
- 复杂度