https://www.lintcode.com/problem/next-closest-time/description
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Solution {
/**
* @param time: the given time
* @return: the next closest time
*/
public String nextClosestTime(String time) {
// write your code here
List<Integer> list = new ArrayList<>();
char[] chars = time.toCharArray();
for (int i = 0; i < time.length(); i++) {
char c = time.charAt(i);
if (Character.isDigit(c)) {
int temp = c - '0';
if (list.indexOf(temp) < 0) {
list.add(temp);
}
}
}
Collections.sort(list);
for (int i = chars.length - 1; i >= 0; i--) {
char c = chars[i];
if (Character.isDigit(c)) {
int temp = c - '0';
int index = list.indexOf(temp) + 1;
if (index == list.size()) {
chars[i] = (char) (list.get(0) + '0');
} else {
char next = (char) (list.get(index) + '0');
if (i == 4) {
chars[i] = next;
return String.valueOf(chars);
} else if (i == 3 && next <= '5') {
chars[i] = next;
return String.valueOf(chars);
} else if (i == 1 && (chars[0] != '2' || chars[0] == '2' && next < '4')) {
chars[i] = next;
return String.valueOf(chars);
} else if (i == 0 && next < '2') {
chars[i] = next;
return String.valueOf(next);
}
chars[i] = (char) (list.get(0) + '0');
}
}
}
return String.valueOf(chars);
}
}
网友评论