The count-and-say sequence is a sequence of digit strings defined by the recursive formula:

To determine how you “say” a digit string, split it into the minimal number of groups so that each group is a contiguous section of all the same character. Then for each group, say the number of characters, then say the character.

To convert the saying into a digit string, replace the counts with a number and concatenate every saying.

For example, the saying and conversion for digit string “3322251”:

"3322251"

two 3's, three 2's, one 5, one 1

2 3+3 2+1 5+1 1

"23321511"

Given a positive integer n, return the nth term of the count-and-say sequence.


Test Cases

Example 1:

Input: n = 1
Output: "1"
Explanation: This is the base case.

Example 2:

Input: n = 4
Output: "1211"
Explanation:
countAndSay(1) = "1"
countAndSay(2) = say "1" = one 1 = "11"
countAndSay(3) = say "11" = two 1's = "21"
countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"

Solution

class Solution {
    public String countAndSay(int n) {
        String prev = "1";
        if (n==1) return prev;
        for(int k=2; k<=n; k++) {
            StringBuilder sb = new StringBuilder();
            int count = 1;
            for(int i=1; i<prev.length(); i++) {
                if (prev.charAt(i) == prev.charAt(i-1)) {
                    count++;
                } else {
                    sb.append(count).append(prev.charAt(i-1));
                    count = 1;
                }
            }
            sb.append(count).append(prev.charAt(prev.length()-1));
            prev = sb.toString();
        }
        return prev;
    }
}
Time Complexity: O(n)
Space Complexity: O(1)