Concise Java Solution


  • 2
    public String nextClosestTime(String s) {
        int[] time = new int[]{Integer.parseInt(s.substring(0,2)), Integer.parseInt(s.substring(3))};
        for (int i=time[0]; i<48; i++) 
            for (int j= i == time[0] ? time[1] + 1 : 0; j<60; j++) 
                if (isValid(s, String.format("%02d", i % 24)) && isValid(s, String.format("%02d", j))) 
                    return String.format("%02d", i % 24) + ":" + String.format("%02d", j);
        return "";
    }
    
    public boolean isValid(String time, String newTime) {
        for (char c : newTime.toCharArray()) 
            if (time.indexOf(c) == -1) return false;
        return true;
    }
    

  • 2

    @compton_scatter said in Concise Java Solution:

    public String nextClosestTime(String s) {
        int[] time = new int[]{Integer.parseInt(s.substring(0,2)), Integer.parseInt(s.substring(3))};
        for (int i=time[0]; i<48; i++) 
            for (int j= i == time[0] ? time[1] + 1 : 0; j<60; j++) 
                if (isValid(s, String.format("%02d", i % 24)) && isValid(s, String.format("%02d", j))) 
                    return String.format("%02d", i % 24) + ":" + String.format("%02d", j);
        return "";
    }
    

    More concise and maybe clearer:

        public String nextClosestTime(String s) {
            int H = Integer.parseInt(s.substring(0,2)), M = Integer.parseInt(s.substring(3));
            String t;
            for (int h=H; true; h++)
                for (int m= h == H ? M + 1 : 0; m<60; m++)
                    if (isValid(s, t = String.format("%02d:%02d", h % 24, m)))
                        return t;
        }
    

    I'm particularly happy about not having a misleading "default" return statement (it made it look like that's a possible result).


Log in to reply
 

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