LeetCode 题解工作台
有效时间的数目
给你一个长度为 5 的字符串 time ,表示一个电子时钟当前的时间,格式为 "hh:mm" 。 最早 可能的时间是 "00:00" , 最晚 可能的时间是 "23:59" 。 在字符串 time 中,被字符 ? 替换掉的数位是 未知的 ,被替换的数字可能是 0 到 9 中的任何一个。 请你返回一个…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · string·结合·enumeration
答案摘要
我们可以直接枚举从 到 的所有时间,然后判断每个时间是否有效,是则答案加一。 枚举结束后将答案返回即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 string·结合·enumeration 题型思路
题目描述
给你一个长度为 5 的字符串 time ,表示一个电子时钟当前的时间,格式为 "hh:mm" 。最早 可能的时间是 "00:00" ,最晚 可能的时间是 "23:59" 。
在字符串 time 中,被字符 ? 替换掉的数位是 未知的 ,被替换的数字可能是 0 到 9 中的任何一个。
请你返回一个整数 answer ,将每一个 ? 都用 0 到 9 中一个数字替换后,可以得到的有效时间的数目。
示例 1:
输入:time = "?5:00" 输出:2 解释:我们可以将 ? 替换成 0 或 1 ,得到 "05:00" 或者 "15:00" 。注意我们不能替换成 2 ,因为时间 "25:00" 是无效时间。所以我们有两个选择。
示例 2:
输入:time = "0?:0?" 输出:100 解释:两个 ? 都可以被 0 到 9 之间的任意数字替换,所以我们总共有 100 种选择。
示例 3:
输入:time = "??:??" 输出:1440 解释:小时总共有 24 种选择,分钟总共有 60 种选择。所以总共有 24 * 60 = 1440 种选择。
提示:
time是一个长度为5的有效字符串,格式为"hh:mm"。"00" <= hh <= "23""00" <= mm <= "59"- 字符串中有的数位是
'?',需要用0到9之间的数字替换。
解题思路
方法一:枚举
我们可以直接枚举从 到 的所有时间,然后判断每个时间是否有效,是则答案加一。
枚举结束后将答案返回即可。
时间复杂度 ,空间复杂度 。
class Solution:
def countTime(self, time: str) -> int:
def check(s: str, t: str) -> bool:
return all(a == b or b == '?' for a, b in zip(s, t))
return sum(
check(f'{h:02d}:{m:02d}', time) for h in range(24) for m in range(60)
)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(1) in practice because there are at most 4 unknown digits and total combinations never exceed 24*60=1440. Space complexity is O(1) if counting, or O(1440) if storing all valid times. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you recognize that each '?' position is independent within hour and minute limits?
- question_mark
Can you optimize counting instead of generating every time explicitly?
- question_mark
What are the boundary conditions for hours and minutes that could fail naive replacements?
常见陷阱
外企场景- error
Replacing '?' without checking hour > 23 leads to invalid counts.
- error
Ignoring that minute tens place must be 0-5 can overcount possibilities.
- error
Multiplying choices blindly without considering dependency between first and second hour digits.
进阶变体
外企场景- arrow_right_alt
Count valid 12-hour clock times instead of 24-hour times.
- arrow_right_alt
Allow partial unknowns only in hours or only in minutes.
- arrow_right_alt
Return all valid time strings instead of just the count.