-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy path681-next-closest-time.cpp
45 lines (40 loc) · 1.13 KB
/
681-next-closest-time.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
public:
string incrementTime(string time) {
int h = stoi(time.substr(0, 2));
int m = stoi(time.substr(3, 2));
if (++m == 60) {
m = 0;
if (++h == 24) {
h = 0;
}
}
string hstr = to_string(h);
string mstr = to_string(m);
if (h < 10) hstr = "0" + hstr;
if (m < 10) mstr = "0" + mstr;
string result = hstr + ":" + mstr;
return result;
}
string nextClosestTime(string time) {
unordered_set<char> chars;
for (char c : time) chars.insert(c);
string tempTime = time;
string result = time;
while (true) {
string newTime = incrementTime(tempTime);
bool allValid = true;
for (char c : newTime) {
if (chars.find(c) == chars.end()) {
allValid = false;
break;
}
}
if (allValid) {
return newTime;
}
tempTime = newTime;
}
return result;
}
};