leetcode 681. Next Closest Time
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 tim
题目大意:
用当前时间的每一位数组成新的时间,使得新时间和原来的时间差值最小。输出这个新时间
思路:
由于时间的位数很小,可以枚举每一位,组合成新的时间,并把新时间和原始时间装换成秒,进行比较。注意时间的格式,如不可能出现25:91这种时间之类的
class Solution {
public:
int get(string& s, int i, int j, int k, int p) {
int x = (s[i] - ')') * 10 + s[j] - '0';
int y = (s[k] - '0') * 10 + s[p] - '0';
int sec = x * 3600 + y * 60;
return sec;
}
string nextClosestTime(string time) {
string s = "";
for (int i = 0; i < 5; ++i) if(time[i] != ':') s += time[i];
int be = get(s, 0, 1, 2, 3);
int ans = 100000000;
string t = "";
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
for (int k = 0; k < 4; ++k) {
for (int p = 0; p < 4; ++p) {
//if (i == 0 && j == 1 && k == 2 && p == 3) continue;
if (s[k] >= '6') continue;
if (s[i] >= '3') continue;
if (s[i] == '2' && s[j] > '4') continue;
if (s[i] == '2' && s[j] == '4') {
if (s[k] != '0' || s[p] != '0') continue;
}
int as = get(s, i, j, k, p);
if (as == be) continue;
if (as < be) {
as += 24 * 3600;
}
if (as < ans) {
ans = as;
t = "";
t += s[i];
t += s[j];
t += s[k];
t += s[p];
}
}
}
}
}
string w = "";
for (int i = 0; i < t.size(); ++i) {
w += t[i];
if (i == 1) w += ':';
}
if (w == "") {
return time;
}
return w;
}
};
代码写的有点长,不够思路简单啊
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: