LeetCode 题解工作台

有效时间的数目

给你一个长度为 5 的字符串 time ,表示一个电子时钟当前的时间,格式为 "hh:mm" 。 最早 可能的时间是 "00:00" , 最晚 可能的时间是 "23:59" 。 在字符串 time 中,被字符 ? 替换掉的数位是 未知的 ,被替换的数字可能是 0 到 9 中的任何一个。 请你返回一个…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · string·结合·enumeration

bolt

答案摘要

我们可以直接枚举从 到 的所有时间,然后判断每个时间是否有效,是则答案加一。 枚举结束后将答案返回即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 string·结合·enumeration 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个长度为 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 之间的数字替换。
lightbulb

解题思路

方法一:枚举

我们可以直接枚举从 00:0000:0023:5923:59 的所有时间,然后判断每个时间是否有效,是则答案加一。

枚举结束后将答案返回即可。

时间复杂度 O(24×60)O(24 \times 60),空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
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)
        )
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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?

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

有效时间的数目题解:string·结合·enumeration | LeetCode #2437 简单