Medium
Given a time represented in the format “HH:MM”, form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused.
You may assume the given input string is always valid. For example, “01:34”, “12:09” are all valid. “1:34”, “12:9” are all invalid.
Example 1:
Input: "19:34"
Output: "19:39"
Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39,
which occurs 5 minutes later. It is not 19:33, because this occurs 23 hours
and 59 minutes later.
Example 2:
Input: "23:59"
Output: "22:22"
Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22.
It may be assumed that the returned time is next day's time since it is
smaller than the input time numerically.
看的答案,这种方法其实非常Straighforward, 就从给的time string每次加一分钟,然后检查这个新的time适不适合可以由原来的time所有的数字构成。如果可以,自然就是最近的了,因为我们是每次加一分钟这样加上来的。
这个方法有几个地方我不会,所以没想到:
- 一开始把string转换成int赋给hours, minutes, 方便后面的加分钟数;
- String.formart(“%02d:%02d”, hours, minutes)这种用法没有储备,%02d的意思就是保留两位整数,没有的位数补0,这样刚好就构成了hh:mm的格式,可以直接返回。这属于基础知识,但不常用,所以不知道。
- 最后检查curt是不是由time的数字组成的,用到了for循环curt的字符,用String.indexOf()看结果是不是<0来判断,非常方便,但我想不起这个方法,更不要说用它来解决算法题了,还是基础不扎实。
class Solution {
//brute force
//plus 1 minute everytime, check if this time can be constructed by the letter in the given string
//if it can, return it because it's the closest else continue the adding process
public String nextClosestTime(String time) {
int hours = Integer.parseInt(time.substring(0,2));
int mins = Integer.parseInt(time.substring(3,5));
while (true){
mins++;
if (mins == 60){
hours++;
if (hours == 24){
hours =0;
}
mins = 0;
}
String curt = String.format("%02d:%02d", hours, mins);
Boolean valid = true;
for (int i = 0; i < curt.length(); i++){
if (time.indexOf(curt.charAt(i)) < 0){
valid = false;
break;
}
}
if (valid){
return curt;
}
}
}
}