Friday, May 26, 2017

38. Count and Say

The count-and-say sequence is the sequence of integers with the first five terms as following:
1.     1
2.     11
3.     21
4.     1211
5.     111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"



Solution:

If n == 1, we return "1".

Now we start from 2.

We use a StringBuilder prev to store the previous string that we need to count and say.

We maintains count (initialize to 1) and say (initialize to prev.charAt(0)) and traverse this string.

When we find we need to do a count and say, we append count and say to a new StringBuilder curr, and set count back to 1 and say to prev.charAt(j).

Do not forget to add the last count and say after traversing the string.



Code:


public class Solution {
    public String countAndSay(int n) {
        if (n == 1) {
            return "1";
        }
        StringBuilder curr = new StringBuilder("1");
        for (int i = 2; i <= n; i++) {
            StringBuilder prev = curr;
            curr = new StringBuilder();
            int count = 1;
            char say = prev.charAt(0);
            for (int j = 1; j < prev.length(); j++) {
                if (prev.charAt(j) != say) {
                    curr.append(count).append(say);
                    count = 1;
                    say = prev.charAt(j);
                }
                else {
                    count++;
                }
            }
            curr.append(count).append(say);
        }
        return curr.toString();
    }
}