int diff = Integer.MAX_VALUE;
public String nextClosestTime(String time) {
if (time == null || time.length() == 0) {
int[] digit = new int[4];
String[] val = time.split(":");
hour = Integer.parseInt(val[0]);
min = Integer.parseInt(val[1]);
String[] res = new String[1];
getNextClosestTime(digit, 0, new int[4], res);
public void getNextClosestTime(int[] digit, int index, int[] temp, String[] res) {
int curHour = 10 * temp[0] + temp[1];
int curMin = 10 * temp[2] + temp[3];
if (curHour >= 0 && curHour <= 23 && curMin >= 0 && curMin <= 59) {
int curDiff = getDiff(curHour, curMin);
res[0] = formatTime(curHour) + ":" + formatTime(curMin);
for (int i = 0; i < 4; i++) {
getNextClosestTime(digit, index + 1, temp, res);
public int getDiff(int curHour, int curMin) {
int diff1 = 3600 - (60 * hour + min);
int diff2 = 3600 - (60 * curHour + curMin);
return diff2 < diff1 ? diff1 - diff2 : diff1 - diff2 + 3600;
public String formatTime(int time) {
if (time >= 0 && time <= 9) {