Count and Say

This is a simple question. simply follow the instruction and do recursive calls (or iterative call as in the following code)

public class Solution {
    public String countAndSay(int n) {
        int count = 1;
        StringBuilder in = new StringBuilder("1");
        while(count < n) {
            StringBuilder next = new StringBuilder();
            int c = 1;
            char last = in.charAt(0);
            for (int i = 1; i < in.length(); i++) {
                if (in.charAt(i) == last) {
                    c++;
                    continue;
                }
                else {
                    next.append((char)(c+'0'));
                    next.append(last);
                    last = in.charAt(i);
                    c = 1;
                }
            }
            //last char
            next.append((char)(c+'0'));
            next.append(last);
            in = next;
            count++;
        }
        return new String(in);
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s