AC Simple Java Solution using StringBuffer

  • 1

    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){
                count++; //keep track of the same numbers to append before saying the value
                str[i].append(String.valueOf(count)+strArr[j-1]); //append the count along with the (j-1)th value
                count = 1;
         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

    @ashwinangle30 excellent solution

  • 1

    @KUSHAL18 Thanks mate!!!

Log in to reply

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