Saturday, January 7, 2017

Count and Say

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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 sequence.
Note: The sequence of integers will be represented as a string.

/*
This problem is like given an array that satisfies the specific rule transformation, and compute the nth element.

Generate the new sequence based on the current one with two steps.
1. Iterate the current sequence and stop when the later character is different from the previous one and record the times of the previous character.
2. Continue the loop until all the characters and their numbers are recorded.

time:O(n * m), space:O(1), m is the average length of n sequences.
*/

public class Solution {
    public String countAndSay(int n) {
        if (n <= 0) {
            return "";
        }
        String ans = "1";
        for (int i = 1; i < n; i++) {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < ans.length(); j++) {
                int count = 1;
                while (j + 1 < ans.length() && ans.charAt(j + 1) ==                        ans.charAt(j)) {
                    j++;
                    count++;
                }
                sb.append(String.valueOf(count) +                                             String.valueOf(ans.charAt(j)));
            }
            ans = sb.toString();
        }
        return ans;
    }
}

No comments:

Post a Comment