Java solution using TreeSet


  • 0
    X

    Firstly, put all chars in TreeSet
    Start from the digit of mins. If there is no higher value available, then set it to the lowest value.Else, return the time with the last digit of min changed to its closest higher value
    Then the tens of mins, if there is no higher value of the value available is larger than '6' then set it to lowest value. If there is a larger value available, return the time with the higher tens of min + last digit of mins we obtained from previous step.
    Then proceed with the hour part.

    public String nextClosestTime(String time) {
    
            TreeSet<Character> set=new TreeSet<>();
            for(char ch:time.toCharArray())if(ch!=':')set.add(ch);
            if(set.higher(time.charAt(4))!=null)
                return time.substring(0,4)+set.higher(time.charAt(4));
            char min_dig=set.first();
            if(set.higher(time.charAt(3))!=null&&set.higher(time.charAt(3))<'6')
                return time.substring(0,3)+set.higher(time.charAt(3))+min_dig;
            char min_ten=set.first();
            char hour_dig;
            if(time.charAt(0)<'2'){
                if(set.higher(time.charAt(1))!=null)
                    return ""+time.charAt(0)+set.higher(time.charAt(1))+":"+min_ten+min_dig;
                hour_dig=set.first();
            }
            else{
                if(set.higher(time.charAt(1))!=null&&set.higher(time.charAt(1))<'4')
                    return ""+time.charAt(0)+set.higher(time.charAt(1))+":"+min_ten+min_dig;
                hour_dig=set.first();
            }
            if(set.higher(time.charAt(0))!=null&&set.higher(time.charAt(0))<='2')
                return ""+set.higher(time.charAt(0))+hour_dig+":"+min_ten+min_dig;
            else return ""+set.first()+hour_dig+":"+min_ten+min_dig;
        }
    

Log in to reply
 

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