Simple readable Java Solution


  • 0
    A

    public class Solution {
    public String countAndSay(int n) {
    String str = "1";
    int i = 1;

        // For n times
        while(i< n){
            char str_arr[] = str.toCharArray();
            int k = 0; str = ""; 
            
            // Within the string, convert it to array and start analysing each character.
            while(k < str_arr.length){
                // if length of array is 1, answer is "1"
                if(str_arr.length == 1){
                    str = "1" + str_arr[k]; 
                    k+=1;
                }else{
                    // else while the previous character is equal to current character, keep counting.
                    int index = k;int count = 1;
                    // make sure the index doesn't go out of bounds
                    while((index+1 < str_arr.length) && (str_arr[index+1] == str_arr[index])){
                           count++;
                           index++;
                    }
                    // Append count and the character and move the k index to the character after counting.
                    str = str + count + str_arr[index];
                    k = index+1;
                }
            }
          i+=1;
        }
        return str;
    }
    

    }


Log in to reply
 

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