# 38. Count and Say

## 刷题内容

• https://leetcode.com/problems/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"


˼· **- ʱ�临�Ӷ�: O(n)*- �ռ临�Ӷ�: O(1)***

����ҪŪ�����Ŀ����˼n == 1ʱ����1内容描述һ��1���� one 1��n == 2ʱ���ǡ�11内容描述��2��1���� two 1��n == 3ʱ���ǡ�21内容描述1��2��1��1���� one 2 one 1��n == 4ʱ���ǡ�1211内容描述�������ƣ�����д��ѭ��ģ������Ĳ������ɡ�

class Solution {
public:
string countAndSay(int n) {
string str;
str.push_back('0' + 1);
n--;
while(n)
{
string temp;
for(int i = 0;i < str.length();)
{
int j = 0;
while(i + j < str.length() && str[i] == str[j + i])
++j;
temp.push_back('0' + j);
temp.push_back(str[i]);
i += j;
}
--n;
str = temp;
}
return str;
}
};


apachecn/AiLearning