Java Solution for your reference


  • 0
    S

    Code is self explanatory..

     public String countAndSay(int n) {
            
            if(n == 1)
                return "1";
            
            int j;
            String prev = "1";
            for(int i = 2; i <= n; i++){
                
                int count = 1;
                StringBuilder sb = new StringBuilder();
                for(j = 1; j < prev.length(); j++){
                    
                    if(prev.charAt(j) == prev.charAt(j-1) )
                        count++;
                    
                    else{
                        sb.append(count);
                        sb.append(prev.charAt(j-1));
                        count = 1;
                    }
                        
                }
                sb.append(count);
                sb.append(prev.charAt(j-1));
    
                prev = sb.toString();
            }
            
            return prev;
        }
    

Log in to reply
 

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