# Simple and Clean Java Solution

• Store all the digits we have from input string in a sorted character list, and try to increase from the last position of input string to the first, see if there are valid solution. If there is one, break and fill the rest with smallest available character and return.

``````class Solution {
public String nextClosestTime(String time) {
if (time == null || time.length() != 5) return "";
char[] output = time.toCharArray();
for (char c : output) {
if (c == ':') continue;
}
Collections.sort(chars);
int i = 4;
while (i >= 0) {
if (time.charAt(i) != ':') {
char next = getNext(time.charAt(i), chars);
if (isValid(next, i, output)) {
output[i] = next;
break;
}
}
--i;
}
char c = chars.get(0);
while (++i < 5) {
if (i == 2) continue;
output[i] = c;
}
return new String(output);
}
private char getNext(char c, List<Character> chars) {
for (char ch : chars) {
if (ch > c) return ch;
}
return '-';
}
private boolean isValid(char next, int i, char[] output) {
if (next < '0') return false;
switch(i) {
case 0:
return next <= '2';
case 1:
return output[i - 1] == '2' && next <= '3' || output[i - 1] != '2' && next <= '9';
case 3:
return next <= '5';
case 4:
return next <= '9';
}
return false;
}
}
``````

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