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 valid. "1:34", "12:9" are invalid.
Example
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: It may be assumed that the returned time is next day's time since it is smaller than the input time numerically.
分析
这道题并不难,主要需要在构造一个时间字符串的时候需要判断该字符串是否是一个合法的时间。我们可以先使用set<string>存放所有可能合法的字符串,其中必然也包括给的time,set是天然有序的,我们就可以寻找time,time的下一个string就是距离time最近的时间。如果time就是set<string>的最后一个元素,那么下一个就是set<string>的起始位置。
Code
class Solution {
public:
/**
* @param time: the given time
* @return: the next closest time
*/
string nextClosestTime(string &time) {
// write your code here
set<string> timeSet;
vector<char> c;
for (int i = 0; i < time.size(); i ++)
{
if (i == 2)
continue;
int j = 0;
for (j = 0; j < c.size(); j ++)
{
if (c[j] == time[i])
break;
}
if (j == c.size())
{
c.push_back(time[i]);
}
}
string prefix;
getTimeSet(c, timeSet, prefix);
time.erase(time.begin() + 2);
set<string>::iterator it;
string res;
for (it = timeSet.begin(); it != timeSet.end(); it ++)
{
if (*it == time)
{
it ++;
if (it != timeSet.end())
{
res = *it;
break;
}
else
{
res = *timeSet.begin();
break;
}
}
}
res.insert(2, 1, ':');
return res;
}
void getTimeSet(const vector<char>& c, set<string>& timeSet, string prefix)
{
if (prefix.size() == 4)
{
timeSet.insert(prefix);
return;
}
else if (prefix.size() == 0)
{
for (int i = 0; i < c.size(); i ++)
{
if (c[i] <= '2')
{
string tmp =prefix;
tmp.push_back(c[i]);
getTimeSet(c, timeSet, tmp);
}
}
}
else if (prefix.size() == 2)
{
for (int i = 0; i < c.size(); i ++)
{
if (c[i] <= '5')
{
string tmp = prefix;
tmp.push_back(c[i]);
getTimeSet(c, timeSet, tmp);
}
}
}
else if (prefix.size() == 1)
{
for (int i = 0; i < c.size(); i ++)
{
if (prefix[0] == '2')
{
if (c[i] > '3') continue;
string tmp = prefix;
tmp.push_back(c[i]);
getTimeSet(c, timeSet, tmp);
}
else
{
string tmp = prefix;
tmp.push_back(c[i]);
getTimeSet(c, timeSet, tmp);
}
}
}
else
{
for (int i = 0; i < c.size(); i ++)
{
string tmp = prefix;
tmp.push_back(c[i]);
getTimeSet(c, timeSet, tmp);
}
}
return;
}
};
运行效率
Your submission beats 90.00% Submissions!