Separate the Numbers

  • + 0 comments

    Java solution(i feel it need some optimization):

    static boolean thereLeadingZero(String s){
            return s.length() > 1 && s.startsWith("0");  
            }
        
        static boolean validateTokens(String curr_token, String next_token){
            
            if(thereLeadingZero(curr_token) || thereLeadingZero(next_token))
                return false;
                
            long curr = Long.parseLong(curr_token);
            long next = Long.parseLong(next_token);
            return (next - curr) == 1;
            }
        
       
        public static void separateNumbers(String s) {
        int n = s.length();
        int curr_index = 0, curr_len = 1;
        int next_index = 1, next_len = 1;
        String first_token= "";
        
        if(n == 1){
            System.out.println("NO");
            return;
            }
        
        while(true){
            String curr_token = s.substring(curr_index, curr_index + curr_len);
            String next_token = s.substring(next_index, next_index + next_len);
           
            if(curr_index == 0)
                first_token = curr_token;
                    
            if( validateTokens(curr_token, next_token) ){
                
                if(next_index + next_len == n){
                    System.out.println("YES " + first_token);
                    return;
                    }
                curr_index = next_index;
                curr_len = next_len;
                next_index = curr_index + curr_len;
                next_len = curr_len;    
                }
            
            else{
                if( (next_len - curr_len) == 1 ){
                    curr_index = 0;
                    curr_len += 1;
                    next_index = curr_index + curr_len;
                    next_len = curr_len;
                    }
                else{
                    next_len += 1;
                    }        
                }
            
            if(next_index + next_len > n){
                System.out.println("NO");
                return;
                }     
            
            }
            
        }