# easy and clean 3ms C++ code with comment

• ``````class Solution {
public:
string nextClosestTime(string time) {
unordered_set<string> st;
for (int i = 0; i < time.size(); i++) { // put all combinations into the set
for (int j = 0; j < time.size(); j++) {
if (time[i] != ':' && time[j] != ':') {
string m = string(1, time[i]) + string(1, time[j]);
if (m <= "59") {
st.insert(m);
}
}
}
}
string hourStr = time.substr(0, 2), minStr = time.substr(3, 2);
int hour = stoi(hourStr), minute = stoi(minStr);

string resMin = "99";
for (string s : st) {  // check is there any minute larger than current one
if (stoi(s) > minute) { // find the minimum minute larger than current minute
resMin = min(resMin, s);
}
}
if (resMin != "99") return hourStr + ":" + resMin;

string minMinute = *min_element(st.begin(), st.end());
for (int h = (hour + 1) % 24; h != hour; h = (h + 1) % 24) { // find next hour
string hStr = h < 10 ? "0" + to_string(h) : to_string(h);
if (st.count(hStr)) return hStr + ":" + minMinute; // directly append the minimum minute
}
return time; // 22:22 and 00:00 case
}
};
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.