LeetCode 题解工作台
判断一个数的数字计数是否等于数位的值
给你一个下标从 0 开始长度为 n 的字符串 num ,它只包含数字。 如果对于 每个 0 的下标 i ,都满足数位 i 在 num 中出现了 num[i] 次,那么请你返回 true ,否则返回 false 。 示例 1: 输入: num = "1210" 输出: true 解释: num[0] …
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 哈希·表·结合·string
答案摘要
我们可以用一个长度为 的数组 统计字符串 中每个数字出现的次数,然后再枚举字符串 中的每个数字,判断其出现的次数是否等于该数字本身。如果对于所有的数字都满足这个条件,那么返回 ,否则返回 。 时间复杂度 ,空间复杂度 。其中 是字符串 的长度,而 是数字的取值范围,即 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给你一个下标从 0 开始长度为 n 的字符串 num ,它只包含数字。
如果对于 每个 0 <= i < n 的下标 i ,都满足数位 i 在 num 中出现了 num[i]次,那么请你返回 true ,否则返回 false 。
示例 1:
输入:num = "1210" 输出:true 解释: num[0] = '1' 。数字 0 在 num 中出现了一次。 num[1] = '2' 。数字 1 在 num 中出现了两次。 num[2] = '1' 。数字 2 在 num 中出现了一次。 num[3] = '0' 。数字 3 在 num 中出现了零次。 "1210" 满足题目要求条件,所以返回 true 。
示例 2:
输入:num = "030" 输出:false 解释: num[0] = '0' 。数字 0 应该出现 0 次,但是在 num 中出现了两次。 num[1] = '3' 。数字 1 应该出现 3 次,但是在 num 中出现了零次。 num[2] = '0' 。数字 2 在 num 中出现了 0 次。 下标 0 和 1 都违反了题目要求,所以返回 false 。
提示:
n == num.length1 <= n <= 10num只包含数字。
解题思路
方法一:计数 + 枚举
我们可以用一个长度为 的数组 统计字符串 中每个数字出现的次数,然后再枚举字符串 中的每个数字,判断其出现的次数是否等于该数字本身。如果对于所有的数字都满足这个条件,那么返回 ,否则返回 。
时间复杂度 ,空间复杂度 。其中 是字符串 的长度,而 是数字的取值范围,即 。
class Solution:
def digitCount(self, num: str) -> bool:
cnt = Counter(int(x) for x in num)
return all(cnt[i] == int(x) for i, x in enumerate(num))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) due to the need to iterate over the string and create the frequency map. Space complexity is O(n) for the frequency map, where `n` is the length of the string `num`. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for understanding of hash table usage to track digit frequencies.
- question_mark
Check if the candidate can identify potential edge cases and handle them correctly.
- question_mark
Verify the candidate's ability to optimize solutions by recognizing that this problem can be solved in linear time.
常见陷阱
外企场景- error
Forgetting to correctly count the digits in `num` can lead to wrong answers.
- error
Confusing the digit's value with its index in the string.
- error
Not handling edge cases where digits might repeat or be absent.
进阶变体
外企场景- arrow_right_alt
Consider larger numbers where the string length exceeds 10.
- arrow_right_alt
Explore how to handle larger digit ranges with more efficient counting techniques.
- arrow_right_alt
What would happen if the input was allowed to be an arbitrary large number, and how would the approach change?