Using TreeSet really easy to understand


  • 0
    6

    The main idea is to use a Tree set to store the value of each digit, each time try to get the ceiling value of the digit if does not exist, use the smallest value instead.

    class Solution {
        public String nextClosestTime(String s) {
            TreeSet<Character> set = new TreeSet<>();
            for(int i = 0; i < s.length(); i++) {
                if(s.charAt(i) == ':')
                    continue;
                set.add(s.charAt(i));
            }
            boolean find = false;
            char[] res = new char[5];
            for(int i = 4; i >= 0; i--) {
                if(i == 2){
                    res[i] = ':';
                    continue;
                }
                if(!find){
                    Character next = set.ceiling((char)(s.charAt(i)+1));
                    if(next != null && ((i == 4 && next <= '9') || (i == 3 && next < '6') || (i == 0 && next < '3') ||
                    (i == 1 && (s.charAt(0) <= '1' && next <= '9' || s.charAt(0) == '2' && next < '4')))){
                        res[i] = next;
                        find = true;
                    }
                    else{
                        res[i] = set.first();
                    }
                }
                else{
                    res[i] = s.charAt(i);
                }
            }
            return new String(res);
        }
    }
    

Log in to reply
 

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