DEV Community

Cover image for LeetCode: Count and Say
Tisha Agarwal
Tisha Agarwal

Posted on

LeetCode: Count and Say

Question link

It's a MEDIUM LEVEL question. At first I found is tough but after going through the question thrice, I understood the concept.

So, before moving on to my question, I just wanna tell that this question can be done using 2 methods-
(1) Recursion (Optimize method)
(2) For-loop

For solving this question, I haven't used recursion. Instead I used for-loop method as it helped me in understanding the concept more clearly.

JAVA CODE

import java.util.*;
public class Count_and_Say {
    public static void main(String[] args) throws Exception
    {
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter the value of n: ");
        int n=sc.nextInt();
        String s=countAndSay(n);
        System.out.println(s);
    }
    public static String countAndSay(int n) {
        String str="1";

        for(int i=2;i<=n;i++)
        {
            StringBuilder temp=new StringBuilder();
            char prev=str.charAt(0);
            int counter=1;
            for(int j=1;j<str.length();j++)
            {
                char ch=str.charAt(j);
                if(ch!=prev)
                {
                   temp.append(counter).append(prev);
                    prev=ch;
                    counter=1;
                }
                else
                {
                    counter++;
                }
            }
                temp.append(counter).append(prev);
                str=temp.toString();
            }

        return str;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)