Java Easy to Understand Brute-Force Solution


  • 0
    B

    The basic idea is to continuously increase the time until we find a valid time.
    Then, this valid time will be the next closest time.

    public String nextClosestTime(String time) {
            /* Add all digits to a set */
            Set<Integer> s = new HashSet<> ();
            for (int i = 0; i < time.length(); ++i) {
                if (i != 2) s.add(Character.getNumericValue(time.charAt(i)));
            }
            
            /* get the numeric value of hour and minute */
            int hour = Integer.parseInt(time.substring(0, 2));
            int minute = Integer.parseInt(time.substring(3, 5));       
            
            for (int i = 0; i < 24 * 60; ++i) {
                /* increase one minute to the current time */
                if (++minute > 59) {
                    minute = 0;
                    hour++;
                }
                if (hour > 23) {
                    hour = 0;
                }
                
                /* if the set contains every digit of the current time,
                    then the current time is the next closest time */
                if (s.contains(hour % 10) && s.contains(hour / 10) &&
                   s.contains(minute % 10) && s.contains(minute / 10)) {
                    break;
                }
                
            }
            
            /* format the answer to string */
            return String.format("%02d:%02d", hour, minute);
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.