[LeetCode] Latest Time You Can Obtain After Replacing Characters

3114. Latest Time You Can Obtain After Replacing Characters

You are given a string s representing a 12-hour format time where some of the digits (possibly none) are replaced with a "?".

12-hour times are formatted as "HH:MM", where HH is between 00 and 11, and MM is between 00 and 59. The earliest 12-hour time is 00:00, and the latest is 11:59.

You have to replace all the "?" characters in s with digits such that the time we obtain by the resulting string is a valid 12-hour format time and is the latest possible.

Return the resulting string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

class Solution {
bool match(char a, char b, string& s) {
if(s.length() == 1) s = "0" + s;
if(a != '?' and s[0] != a) return false;
if(b != '?' and s[1] != b) return false;
return true;
}
public:
string findLatestTime(string s) {
string t = "", m = "";
for(int i = 0; i < 12; i++) {
string now = to_string(i);
if(match(s[0], s[1], now)) t = now;
}
for(int i = 0; i < 60; i++) {
string now = to_string(i);
if(match(s[3], s[4], now)) m = now;
}
return t + ":" + m;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2024/04/14/PS/LeetCode/latest-time-you-can-obtain-after-replacing-characters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.