Problem description

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.

思路

题意是 n=1 时输出字符串 1;n=2 时,数上次字符串中的数值个数,因为上次字符串有 1 个 1,所以输出 11;n=3 时,由于上次字符是 11,有 2 个 1,所以输出 21;n=4 时,由于上次字符串是 21,有 1 个 2 和 1 个 1,所以输出 1211。依次类推,写个 countAndSay(n) 函数返回字符串。

题意理解之后就好办了,是典型的递归问题,其代码很简单,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
string countAndSay(int n) {
if (n == 1)
return "1";
// transform string into array
string str = countAndSay(n-1) + "*";
int len = str.length();
char carray[len];
strcpy(carray, str.c_str());

int count = 1;
string s = "";

for(int i = 0; i < len - 1; i++){
if(carray[i] == carray[i+1]){
count++;
}
else {
s = s + to_string(count) + carray[i];
count = 1;
}
}
return s;
}
};