LeetCode 题解工作台
替换隐藏数字得到的最晚时间
给你一个字符串 time ,格式为 hh:mm (小时:分钟),其中某几位数字被隐藏(用 ? 表示)。 有效的时间为 00:00 到 23:59 之间的所有时间,包括 00:00 和 23:59 。 替换 time 中隐藏的数字,返回你可以得到的最晚有效时间。 示例 1: 输入: time = "2…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 贪心·invariant
答案摘要
我们依次处理字符串的每一位,处理的规则如下: 1. 第一位:若第二位的值已确定,且值落在区间 $[4, 9]$ 内,那么第一位只能取 ,否则第一位最大取 ;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个字符串 time ,格式为 hh:mm(小时:分钟),其中某几位数字被隐藏(用 ? 表示)。
有效的时间为 00:00 到 23:59 之间的所有时间,包括 00:00 和 23:59 。
替换 time 中隐藏的数字,返回你可以得到的最晚有效时间。
示例 1:
输入:time = "2?:?0" 输出:"23:50" 解释:以数字 '2' 开头的最晚一小时是 23 ,以 '0' 结尾的最晚一分钟是 50 。
示例 2:
输入:time = "0?:3?" 输出:"09:39"
示例 3:
输入:time = "1?:22" 输出:"19:22"
提示:
time的格式为hh:mm- 题目数据保证你可以由输入的字符串生成有效的时间
解题思路
方法一:贪心
我们依次处理字符串的每一位,处理的规则如下:
- 第一位:若第二位的值已确定,且值落在区间 内,那么第一位只能取 ,否则第一位最大取 ;
- 第二位:若第一位的值已确定,且值为 ,那么第二位最大取 ,否则第二位最大取 ;
- 第三位:第三位最大取 ;
- 第四位:第四位最大取 。
时间复杂度 ,空间复杂度 。
class Solution:
def maximumTime(self, time: str) -> str:
t = list(time)
if t[0] == '?':
t[0] = '1' if '4' <= t[1] <= '9' else '2'
if t[1] == '?':
t[1] = '3' if t[0] == '2' else '9'
if t[3] == '?':
t[3] = '5'
if t[4] == '?':
t[4] = '9'
return ''.join(t)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(1) since the string has a fixed length of 5 characters, and each '?' requires at most a few constant checks. Space complexity is O(1) as only a few variables are needed for construction. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Identifying that a brute-force solution is unnecessary due to the fixed-length string.
- question_mark
Recognizing the pattern as greedy plus invariant validation.
- question_mark
Expecting careful digit-by-digit reasoning to avoid invalid hours or minutes.
常见陷阱
外企场景- error
Choosing the largest digit without validating the resulting time, which may produce an invalid hour or minute.
- error
Ignoring the dependency between the first and second hour digits when the first is '2'.
- error
Overcomplicating by attempting full enumeration instead of greedy choice.
进阶变体
外企场景- arrow_right_alt
Maximize the earliest valid time instead of the latest by reversing greedy choices.
- arrow_right_alt
Handle a 12-hour format with hidden digits and AM/PM markers.
- arrow_right_alt
Replace hidden digits in a larger timestamp string including seconds.