Fast java solution


  • 0
    Z
    class Solution {
        public String nextClosestTime(String time) {
            char[] digits = new char[4];
            digits[0] = time.charAt(0);
            digits[1] = time.charAt(1);
            digits[2] = time.charAt(3);
            digits[3] = time.charAt(4);
            Arrays.sort(digits);
    
            for (int i = 0; i < 4; i++) {
                if (digits[i] > time.charAt(4)) {
                    return time.substring(0, 4) + digits[i];
                }
            }
        
            for (int i = 0; i < 4; i++) {
                if (digits[i] > time.charAt(3) && digits[i] < '6') {
                    return time.substring(0, 3) + digits[i] + digits[0];
                }
            }
            
            for (int i = 0; i < 4; i++) {
                if (digits[i] > time.charAt(1)) {
                    if (time.charAt(0) == '2' && digits[i] > '3') {
                        continue;
                    }
                    return "" + time.charAt(0) + digits[i] + ":" +digits[0] + digits[0];
                }
            }
            
            for (int i = 0; i < 4; i++) {
                if (digits[i] > time.charAt(0)) {
                    if (digits[i] > '2' || (digits[i] == '2' && time.charAt(1) > '3')) {
                        continue;
                    }
                    return "" + digits[i] + digits[0] + ":" + digits[0] + digits[0];
                }
            }
            
            return "" + digits[0] + digits[0] + ":" + digits[0] + digits[0];
        }
    }
    

Log in to reply
 

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