[LeetCode] 2437. Number of Valid Clock Times

发布时间 2023-05-09 10:56:26作者: CNoodle

You are given a string of length 5 called time, representing the current time on a digital clock in the format "hh:mm". The earliest possible time is "00:00" and the latest possible time is "23:59".

In the string time, the digits represented by the ? symbol are unknown, and must be replaced with a digit from 0 to 9.

Return an integer answer, the number of valid clock times that can be created by replacing every ? with a digit from 0 to 9.

Example 1:

Input: time = "?5:00"
Output: 2
Explanation: We can replace the ? with either a 0 or 1, producing "05:00" or "15:00". Note that we cannot replace it with a 2, since the time "25:00" is invalid. In total, we have two choices.

Example 2:

Input: time = "0?:0?"
Output: 100
Explanation: Each ? can be replaced by any digit from 0 to 9, so we have 100 total choices.

Example 3:

Input: time = "??:??"
Output: 1440
Explanation: There are 24 possible choices for the hours, and 60 possible choices for the minutes. In total, we have 24 * 60 = 1440 choices.

Constraints:

  • time is a valid string of length 5 in the format "hh:mm".
  • "00" <= hh <= "23"
  • "00" <= mm <= "59"
  • Some of the digits might be replaced with '?' and need to be replaced with digits from 0 to 9.

有效时间的数目。

给你一个长度为 5 的字符串 time ,表示一个电子时钟当前的时间,格式为 "hh:mm" 。最早 可能的时间是 "00:00" ,最晚 可能的时间是 "23:59" 。

在字符串 time 中,被字符 ? 替换掉的数位是 未知的 ,被替换的数字可能是 0 到 9 中的任何一个。

请你返回一个整数 answer ,将每一个 ? 都用 0 到 9 中一个数字替换后,可以得到的有效时间的数目。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/number-of-valid-clock-times
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是枚举。题意是给一个长度为 5 的字符串表示的时间,里面有些 digit 可能会被问号替代,如果把问号改回数字,请问有多少种不同的组合。

我们遍历字符串,分别考虑每一个位置出现问号能产生的组合。注意无论是小时的部分还是分钟的部分,都需要综合考虑两个 digit 的情况,具体判断的条件参见代码。

时间O(1)

空间O(1)

Java实现

 1 class Solution {
 2     public int countTime(String time) {
 3         char a = time.charAt(0);
 4         char b = time.charAt(1);
 5         char c = time.charAt(3);
 6         char d = time.charAt(4);
 7         int h = 1;
 8         int m = 1;
 9         if (a == '?' && b == '?') {
10             h = 24;
11         } else if (a == '?' && b != '?') {
12             if (b >= '0' && b <= '3') {
13                 h = 3;
14             } else {
15                 h = 2;
16             }
17         } else if (a != '?' && b == '?') {
18             if (a == '0' || a == '1') {
19                 h = 10;
20             } else if (a == '2') {
21                 h = 4;
22             }
23         }
24         
25         if (c == '?' && d == '?') {
26             m = 60;
27         } else if (c == '?' && d != '?') {
28             m = 6;
29         } else if (c != '?' && d == '?') {
30             m = 10;
31         }
32         return h * m;
33     }
34 }

 

LeetCode 题目总结