Advertisement
jiazhongchen

leetcode681

Feb 12th, 2022
1,305
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     string nextClosestTime(string time) {
  4.         vector<int> vi;
  5.         for (char c : time) {
  6.             if (c == ':') continue;
  7.             vi.push_back(c - '0');
  8.         }
  9.         int hh = vi[0] * 10 + vi[1];
  10.         int mm = vi[2] * 10 + vi[3];
  11.         int original = hh * 60 + mm;
  12.         sort(vi.begin(), vi.end());
  13.         int ans = INT_MAX;
  14.         set<int> candidates;
  15.         for (int i = 0; i < 4; ++i) {
  16.             for (int j = 0; j < 4; ++j) {
  17.                 for (int k = 0; k < 4; ++k) {
  18.                     for (int l = 0; l < 4; ++l) {
  19.                         int hh = vi[i] * 10 + vi[j];
  20.                         int mm = vi[k] * 10 + vi[l];
  21.                         if (hh >= 24 || mm >= 60) continue;
  22.                         int candidate = hh * 60 + mm;
  23.                         if (candidate <= 1440) {
  24.                             candidates.insert(candidate);
  25.                         }
  26.                     }
  27.                 }
  28.             }
  29.         }
  30.         for (auto candidate : candidates) {
  31.             if (candidate > original) {
  32.                 ans = min(ans, candidate);
  33.             }
  34.         }
  35.         if (ans == INT_MAX) {
  36.             ans = *(candidates.begin());
  37.         }
  38.         hh = ans / 60;
  39.         mm = ans % 60;
  40.         string str_hh = hh < 10 ? "0" + to_string(hh) : to_string(hh);
  41.         string str_mm = mm < 10 ? "0" + to_string(mm) : to_string(mm);
  42.         return str_hh + ":" + str_mm;
  43.     }
  44. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement