Self Explained Java Solution


  • 0
    K

    Starting from right to left, try to replace current digit with a valid ceiling digit. If no valid ceiling digit is available, replace current digit with the min digit.

    private class Digits {
        List<Integer> digits = new ArrayList<Integer>();
        
        private Digits(String time) {
            for (int i = 0; i < time.length(); i++) {
                if (time.charAt(i) != ':') {
                    digits.add((int)(time.charAt(i)-'0'));
                }
            }
            Collections.sort(digits);
        }
        
        private Integer getCeiling(int num) {
            for (int i = 0; i < digits.size(); i++)
                if(digits.get(i) > num)
                    return digits.get(i);
            return null;
        }
        
        private Integer getMin() {
            return digits.isEmpty() ? null : digits.get(0);
        }
    }
    
    public String nextClosestTime(String time) {
        Digits digits = new Digits(time);
        StringBuilder sb = new StringBuilder(time);
        for (int i = sb.length()-1; i >= 0; i--) {
            if (sb.charAt(i) != ':') {
                Integer ceiling = digits.getCeiling((int)(sb.charAt(i)-'0'));
                if (ceiling != null) {
                    sb.setCharAt(i, (char)(ceiling+'0'));
                    if (valid(sb.toString()))
                        return sb.toString();
                }
                sb.setCharAt(i, (char)(digits.getMin()+'0'));
            }
        }
        return sb.toString();
    }
    
    private boolean valid(String s) {
        return Integer.parseInt(s.substring(0, 2)) <= 23 && Integer.parseInt(s.substring(3)) <= 59;
    }

Log in to reply
 

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