Java method


  • 0
    C
     public String nextClosestTime(String time) {
            
            List<Integer> list = new ArrayList<>();
            int[] number = new int[4];
            int index = 0;
            
            for (char c: time.toCharArray()){
                if (c >= '0' && c <= '9'){
                    int temp = c - '0';
                    if (!list.contains(temp)){
                        list.add(temp);
                    }
                    number[index++] = temp;
                }
            }
            
            Collections.sort(list);
            int size = list.size();
            
            for (int i = 3; i >= 0; i--){
                
                int cur = number[i];
                int k = Collections.binarySearch(list, cur);
                int[] pre = new int[]{10*number[0] + number[1], 10*number[2]+number[3]};
                
                for (int j = k + 1; ; j++){
                    int temp = j % size;
                    
                    // change the number of current
                    number[i] = list.get(temp);
                    
                    if (isValid(number)){
                        break;
                    }
                    
                    number[i] = cur;
                    
                }
                
                if (10*number[0] + number[1] > pre[0] || 10*number[2] + number[3] > pre[1]){
                    break;
                }
                
            }
            
            StringBuilder sb = new StringBuilder();
            sb.append(number[0]).append(number[1]).append(":").append(number[2]).append(number[3]);
            
            return sb.toString();
            
            
        }
        
        public boolean isValid(int[] number){
            
            if (number[0] * 10 + number[1] >= 24){
                return false;
            }
            
            if (number[2] * 10 + number[3] >= 59){
                return false;
            }
            
            return true;
            
        }
    

Log in to reply
 

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