# 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 where 1 ≤ n ≤ 30, 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

Approach 1: Scan the string and count each repeated segment.

# Code (Python)

Approach 1:

# Code (C++)

Approach 1:

class Solution {
public:
    string countAndSay(int n) {
        string str = "1";
        for (int i = 1; i < n; ++i)
        {
            char head = str[0];
            int count = 1;
            string tmp = "";
            for (int j = 1; j < str.size(); ++j)
            {
                if (str[j] == head)
                    count++;
                else
                {
                    tmp = tmp + char('0' + count) + head;
                    head = str[j];
                    count = 1;
                }
            }
            str = tmp + char('0' + count) + head; // Do another concatenation when reaching the end of the string.
        }
        return str;
    }
};

class Solution {
public:
    string countAndSay(int n) {
        string str = "1";
        for (int i = 1; i < n; ++i)
        {
            ostringstream oss;
            int head = 0;
            for (int j = 1; j <= str.size(); ++j)
            {
                if (j == str.size() || str[j] != str[head])
                {
                    oss << j - head << str[head];
                    head = j;
                }
            }
            str = oss.str();
        }
        return str;
    }
};