fork(1) download
  1. //https://l...content-available-to-author-only...e.com/problems/next-closest-time/
  2.  
  3. /* LC 681 Medium - Next Closest Time - Google Interview Question
  4. Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits.
  5. There is no limit on how many times a digit can be reused.
  6.  
  7. You may assume the given input string is always valid.
  8. For example, "01:34", "12:09" are all valid. "1:34", "12:9" are all invalid.
  9. Example 1:
  10.  
  11. Input: "19:34"
  12. Output: "19:39"
  13. Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later.
  14. It is not 19:33, because this occurs 23 hours and 59 minutes later.
  15. **/
  16.  
  17. import java.util.HashSet;
  18. import java.util.Set;
  19.  
  20. class NextClosestTime {
  21. public String nextClosestTime(String time) {
  22. int minutes = Integer.parseInt(time.substring(0, 2)) * 60 + Integer.parseInt(time.substring(3));
  23. Set<Integer> digits = new HashSet<>();
  24. for (char c : time.toCharArray())
  25. if (c != ':')
  26. digits.add(Character.digit(c, 10));
  27. while (true) {
  28. minutes = (minutes + 1) % (24 * 60);
  29. int[] nextTime = {
  30. minutes / 60 / 10,
  31. minutes / 60 % 10,
  32. minutes % 60 / 10,
  33. minutes % 60 % 10
  34. };
  35. boolean valid = true;
  36. for (int digit : nextTime)
  37. if (!digits.contains(digit))
  38. valid = false;
  39. if (valid)
  40. return String.format("%02d:%02d", minutes / 60, minutes % 60);
  41. }
  42. }
  43.  
  44. public static void main(String[] args) {
  45. NextClosestTime ob = new NextClosestTime();
  46. System.out.println(ob.nextClosestTime("19:34"));
  47. System.out.println(ob.nextClosestTime("23:59"));
  48. }
  49. }
Success #stdin #stdout 0.05s 2184192KB
stdin
Standard input is empty
stdout
19:39
22:22