Guest User

Untitled

a guest
Feb 21st, 2018
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. import java.util.HashSet;
  2. import java.util.Set;
  3.  
  4. class Solution {
  5. public String nextClosestTime(String current) {
  6. // Get the digits from input
  7. Set<Integer> set = new HashSet<>();
  8.  
  9. for (int i = 0; i < current.length(); i++) {
  10. if (current.charAt(i) == ':') continue;
  11. set.add(Character.getNumericValue(current.charAt(i)));
  12. }
  13.  
  14. // Convert current time to integer representation
  15. int idx = current.indexOf(':');
  16. int curr = Integer.valueOf(current.substring(0, idx)) * 60 + Integer.valueOf(current.substring(idx + 1));
  17.  
  18. // Going through each time point and validate whether all digits
  19. // are valid
  20. int[] result = new int[4];
  21.  
  22. // Store each base in an array
  23. // A number [0, 1440) divide corresponding base gives the digit at that position
  24. int[] base = new int[] {600, 60, 10, 1};
  25.  
  26. for (int i = 1; i <= 1440; i++) {
  27. // Increment current time incrementally for a full cycle
  28. int next = (curr + i) % 1440;
  29.  
  30. // Check each digit in the next time point
  31. int j = 0; // Number of digit are fixed in the result
  32.  
  33. while (j < 4) {
  34. int d = next / base[j];
  35. if (!set.contains(d)) break;
  36. result[j] = d;
  37. next = next % base[j];
  38. j++;
  39. }
  40.  
  41. if (j == 4) {
  42. break;
  43. } else {
  44. // Clean up
  45. result = new int[4];
  46. }
  47. }
  48.  
  49. return String.valueOf(result[0]) + String.valueOf(result[1]) + ":" + String.valueOf(result[2]) + String.valueOf(result[3]);
  50. }
  51. }
Add Comment
Please, Sign In to add comment