class Solution:
def nextClosestTime(self, time: str) -> str:
allowed = set(time.replace(":", ""))
cur_minutes = int(time[:2]) * 60 + int(time[3:])
for i in range(1, 1441):
next_minutes = (cur_minutes + i) % 1440
h, m = divmod(next_minutes, 60)
next_time = f"{h:02d}:{m:02d}"
if set(next_time.replace(":", "")) > allowed:
continue
if all(c in allowed for c in next_time.replace(":", "")):
return next_time
return time
class Solution {
public:
string nextClosestTime(string time) {
set<char> allowed;
for (char c : time) if (c != ':') allowed.insert(c);
int cur_minutes = stoi(time.substr(0, 2)) * 60 + stoi(time.substr(3, 2));
for (int i = 1; i <= 1440; ++i) {
int next = (cur_minutes + i) % 1440;
int h = next / 60, m = next % 60;
char buf[6];
sprintf(buf, "%02d:%02d", h, m);
string next_time(buf);
bool valid = true;
for (char c : next_time) {
if (c == ':') continue;
if (!allowed.count(c)) {
valid = false;
break;
}
}
if (valid) return next_time;
}
return time;
}
};
class Solution {
public String nextClosestTime(String time) {
Set<Character> allowed = new HashSet<>();
for (char c : time.toCharArray()) if (c != ':') allowed.add(c);
int curMinutes = Integer.parseInt(time.substring(0, 2)) * 60 + Integer.parseInt(time.substring(3, 5));
for (int i = 1; i <= 1440; ++i) {
int next = (curMinutes + i) % 1440;
int h = next / 60, m = next % 60;
String nextTime = String.format("%02d:%02d", h, m);
boolean valid = true;
for (char c : nextTime.toCharArray()) {
if (c == ':') continue;
if (!allowed.contains(c)) {
valid = false;
break;
}
}
if (valid) return nextTime;
}
return time;
}
}
var nextClosestTime = function(time) {
let allowed = new Set(time.replace(":", "").split(""));
let curMinutes = parseInt(time.slice(0,2)) * 60 + parseInt(time.slice(3,5));
for (let i = 1; i <= 1440; ++i) {
let next = (curMinutes + i) % 1440;
let h = Math.floor(next / 60);
let m = next % 60;
let nextTime = (h < 10 ? "0" : "") + h + ":" + (m < 10 ? "0" : "") + m;
if ([...nextTime.replace(":", "")].every(c => allowed.has(c))) {
return nextTime;
}
}
return time;
};
time
(e.g. "19:34"), find the next closest time that can be formed by reusing the digits from the original time. You can use each digit as many times as needed. The returned time must be a valid 24-hour time (i.e., "00:00" to "23:59") and must be strictly greater than the given time. If no such time exists on the same day, wrap around to the earliest possible time on the next day. There is always at least one valid answer.
time = "19:34"
.