Tuesday, December 4, 2018

681. Next Closest Time

Although it is not used here, there's a very handy format method
String.format("%02d:%02d", resHour, resMinute);
Will pad leading zero to time


100.00 %
class Solution {
    public String nextClosestTime(String time) {
int[] list = new int[4];
list[0] = time.charAt(0) - '0';
list[1] = time.charAt(1) - '0';
list[2] = time.charAt(3) - '0';
list[3] = time.charAt(4) - '0';
Arrays.sort(list);
char[] chars = time.toCharArray();
for (int i = time.length() - 1; i >= 0; i--) {
if (i == 2) {
continue;
}
for (int m : list) {
if (m > chars[i] - '0') {
chars[i] = (char)(m + '0');
if (isValid(chars)) {
return new String(chars);
}
}
}
chars[i] = (char)(list[0] + '0');
}
return new String(chars);
}

private boolean isValid(char[] chars) {
int hour = (chars[0] - '0') * 10 + (chars[1] - '0');
int minute = (chars[3] - '0') * 10 + (chars[4] - '0');
return hour < 24 && minute < 60;
}
}

No comments:

Post a Comment