LeetCode 题解工作台

替换隐藏数字得到的最晚时间

给你一个字符串 time ,格式为 hh:mm (小时:分钟),其中某几位数字被隐藏(用 ? 表示)。 有效的时间为 00:00 到 23:59 之间的所有时间,包括 00:00 和 23:59 。 替换 time 中隐藏的数字,返回你可以得到的最晚有效时间。 示例 1: 输入: time = "2…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 贪心·invariant

bolt

答案摘要

我们依次处理字符串的每一位,处理的规则如下: 1. 第一位:若第二位的值已确定,且值落在区间 $[4, 9]$ 内,那么第一位只能取 ,否则第一位最大取 ;

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 time ,格式为 hh:mm(小时:分钟),其中某几位数字被隐藏(用 ? 表示)。

有效的时间为 00:0023:59 之间的所有时间,包括 00:0023: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
  • 题目数据保证你可以由输入的字符串生成有效的时间
lightbulb

解题思路

方法一:贪心

我们依次处理字符串的每一位,处理的规则如下:

  1. 第一位:若第二位的值已确定,且值落在区间 [4,9][4, 9] 内,那么第一位只能取 11,否则第一位最大取 22
  2. 第二位:若第一位的值已确定,且值为 22,那么第二位最大取 33,否则第二位最大取 99
  3. 第三位:第三位最大取 55
  4. 第四位:第四位最大取 99

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
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)
speed

复杂度分析

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

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

替换隐藏数字得到的最晚时间题解:贪心·invariant | LeetCode #1736 简单