题目描述
警察在侦破一个案件时,得到了线人给出的可能犯罪时间,形如 “HH:MM” 表示的时刻。
根据警察和线人的约定,为了隐蔽,该时间是修改过的,
解密规则为:利用当前出现过的数字,构造下一个距离当前时间最近的时刻,则该时间为可能的犯罪时间。
每个出现数字都可以被无限次使用。
输入描述
形如HH:SS字符串,表示原始输入。
输出描述
形如HH:SS的字符串,表示推理处理的犯罪时间。
备注
1.可以保证现任给定的字符串一定是合法的。
例如,“01:35”和“11:08”是合法的,“1:35”和“11:8”是不合法的。
2.最近的时刻可能在第二天。
用例
输入 | 输出 |
---|---|
20:12 | 20:20 |
23:59 | 22:22 |
12:58 | 15:11 |
18:52 | 18:55 |
23:52 | 23:53 |
09:17 | 09:19 |
07:08 | 08:00 |
#include <algorithm>
#include <string>
#include <iostream>
#include <set>
using namespace std;int main() {string str;cin >> str;int pos = str.find(':');if (pos > 0){str.erase(pos, 1);}set<string> set; //去重和排序for (auto c1:str){if (c1 > '2')continue;for (auto c2 : str){if (c1 == '2' && c2 > '3')continue;for (auto c3 : str){if (c3 > '5')continue;for (auto c4 : str){string s;s.push_back(c1);s.push_back(c2);s.push_back(c3);s.push_back(c4);set.insert(s);}}}}//查找下一个string result;auto it = set.find(str);if (++it != set.end()){result = *it;}else {result = *(set.begin());}cout << result.substr(0, 2) << ":" << result.substr(2, 2) << endl;system("pause");return 0;
}
用例评测通过率100%.
当然也可以用正则表达式来判断时间格式是否合法。
下面是从网上搜索到的某位大佬的解法:
using namespace std;regex pattern("(([01][0-9])|([2][0-3]))[0-5][0-9]");void dfs(vector<char> &arr, const string &path, vector<string> &res) {if (path.size() == 4) {if (regex_match(path, pattern)) {res.emplace_back(path);}return;}for (const auto &c: arr) {dfs(arr, path + c, res);}
}int main() {string s;cin >> s;string hour = s.substr(0, 2);string minute = s.substr(3, 2);set<char> charSet;for (const auto &c: hour) {charSet.insert(c);}for (const auto &c: minute) {charSet.insert(c);}vector<char> charArr;for (const auto &c: charSet) {charArr.emplace_back(c);}vector<string> res;dfs(charArr, "", res);sort(res.begin(), res.end());string curTime = hour + minute;int i = 0;for (; i < res.size(); i++) {if (res[i] == curTime) {break;}}string ans;if (i == res.size() - 1) {ans = res[0];} else {ans = res[i + 1];}cout << ans.substr(0, 2) << ":" << ans.substr(2) << endl;return 0;
}