DEV Community

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

Posted on

3 3

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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay