Super Simple solution in Java


  • 1

    No explanation required.

    public String countAndSay(int n) {
            if(n==1) return "1";
            String s="1";
            for(int i=2;i<=n;i++){
                StringBuilder temp = new StringBuilder();
                int j=1,count=1;
                char prev=s.charAt(0);
                while(j<s.length()){
                    char next = s.charAt(j);
                    if(next==prev) count++;
                    else{
                        temp.append(count);
                        temp.append(prev);
                        count=1;
                    }
                    prev=next;
                    j++;
                }
                if(count>0) {
                    temp.append(count);
                    temp.append(prev);
                }
                s=temp.toString();
            }
            return s;
        }
    

Log in to reply
 

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