Count and Say



Problem to find the n th value of Count and Say pattern.



Example-1:


Input    : n = "5"
Output   : "111221"
Explain  : step 1 : Initially s = 1
           step 2 : s = one 1's ==>  So s = 11
           step 3 : s = two 1's ==> So s = 21
           step 4 : s = one 2's and one 1's ==> So s = 1211
           step 5 : s = one 1's and one 2's and two 1's ==> So s = 111221  


Example-2:


Input    : n = 4
Output   : "1211"
Explain  : step 1 : Initially s = 1
           step 2 : s = one 1's ==>  So s = 11
           step 3 : s = two 1's ==> So s = 21
           step 4 : s = one 2's and one 1's ==> So s = 1211







Solution




public class Main
{
    public static void main(String [] args)
    {
        int n = 5;

        String s = "1";

        while(n != 1)
        {
            s = solve(s);

            n--;
        }

        System.out.print(s);
    }

    public static String solve(String str)
    {
        int count = 1;

        String s_new = "";

        for(int i = 0; i < str.length(); i++)
        {
            if(i != str.length()-1 && str.charAt(i) == str.charAt(i+1)){

                count++;
            }

            else{

                s_new = s_new + count + str.charAt(i);  

                count = 1;

            }
        }

        return s_new;
    } 
}
n = 5

k = "1 "

if(n == 1):

    print("1")

for i in range(n-1):

    count = 1

    d = ""

    for j in range(1,len(k)):

        if(k[j-1] == k[j]):

            count += 1

        else:

            d += str(count)

            d += str(k[j-1])

            count = 1

    d += " "

    k = d

print(d.strip())



Output



111221