AC Simple Java Solution using StringBuffer


  • 1
    A

    public class Solution {
    public String countAndSay(int n) {

     StringBuffer[] str = new StringBuffer[n]; // Create a buffer of size n as to say nth value we need (n-1)th value
     str[0] = new StringBuffer("1"); // Assign the 1st element as 1
     
     for(int i = 1; i < n; i++){
         str[i] = new StringBuffer(""); 
         char strArr[] = str[i-1].toString().toCharArray();// Use the (i-1)th value to say ith value
         int len = strArr.length;
         int count = 1;
         
         int j = 1;
         while(j < len){
            
            if(strArr[j]==strArr[j-1]){
                count++; //keep track of the same numbers to append before saying the value
            }else{
                str[i].append(String.valueOf(count)+strArr[j-1]); //append the count along with the (j-1)th value
                count = 1;
            }
            j++;
         }
    
         str[i].append(String.valueOf(count)+strArr[j-1]); //Last append the final count and (j-1)th value
     }
     
     return str[n-1].toString();   
    }
    

    }


  • 1
    K

    @ashwinangle30 excellent solution


  • 1
    A

    @KUSHAL18 Thanks mate!!!


Log in to reply
 

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