Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashSet;
- import java.util.Set;
- class Solution {
- public String nextClosestTime(String current) {
- // Get the digits from input
- Set<Integer> set = new HashSet<>();
- for (int i = 0; i < current.length(); i++) {
- if (current.charAt(i) == ':') continue;
- set.add(Character.getNumericValue(current.charAt(i)));
- }
- // Convert current time to integer representation
- int idx = current.indexOf(':');
- int curr = Integer.valueOf(current.substring(0, idx)) * 60 + Integer.valueOf(current.substring(idx + 1));
- // Going through each time point and validate whether all digits
- // are valid
- int[] result = new int[4];
- // Store each base in an array
- // A number [0, 1440) divide corresponding base gives the digit at that position
- int[] base = new int[] {600, 60, 10, 1};
- for (int i = 1; i <= 1440; i++) {
- // Increment current time incrementally for a full cycle
- int next = (curr + i) % 1440;
- // Check each digit in the next time point
- int j = 0; // Number of digit are fixed in the result
- while (j < 4) {
- int d = next / base[j];
- if (!set.contains(d)) break;
- result[j] = d;
- next = next % base[j];
- j++;
- }
- if (j == 4) {
- break;
- } else {
- // Clean up
- result = new int[4];
- }
- }
- return String.valueOf(result[0]) + String.valueOf(result[1]) + ":" + String.valueOf(result[2]) + String.valueOf(result[3]);
- }
- }
Add Comment
Please, Sign In to add comment