Easy Java Solution By TreeSet


  • 0
    D
        TreeSet<Integer> set = new TreeSet<>();
        char[] times = time.toCharArray();
        
        int min = 10;
        
        for(char c : times) {
            if(c != ':') {
                int num = c - '0';
                set.add(num);
                min = Math.min(min, num);
            }
        }
        
        for(int i = 4; i >= 0; i--) {
            if(times[i] == ':') {
                continue;
            }
            int num = times[i] - '0';
            Integer larger = set.higher(num);
            if(larger != null) {
                if(i == 4 && larger <= 9) {
                    times[i] = (char)(larger + '0');
                    return new String(times);
                } else if(i == 3 && larger <= 5) {
                    times[i] = (char)(larger + '0');
                    times[4] = (char)(min + '0');
                    return new String(times);
                } else if(i == 1 && ((times[0] == '2' && larger <= 3) || (times[0] <= '1' && larger <= 9))) {
                    times[i] = (char)(larger + '0');
                    times[3] = times[4] = (char)(min + '0');
                    return new String(times);
                } else if(i == 0 && larger <= 2) {
                    times[1] = times[3] = times[4] = (char)(min + '0');
                    times[i] = (char)(larger + '0');
                    return new String(times);
                }
            }
        }
        
        times[0] = times[1] = times[3] = times[4] = (char)(min + '0');
        
        return new String(times);

Log in to reply
 

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