題目描述
警察在偵破一個案件時,得到了線人給出的可能犯罪時間,形如 “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;
}