题目大意
数数字的个数:
- 1
- 11(1个1)
- 21(2个1)
- 1211(1个2,2个1)
以此类推
解题思路
利用递归,得出n-1的字符串,然后遍历数组进行数数即可,注意递归的退出条件即可
代码
string countAndSay(int n) {
string newResult = "";
if (n == 1) {
return "1";
} else if (n == 2) {
return "11";
} else {
string lastResult = countAndSay(n - 1);
int count = 1;
for (int i = 1; i < lastResult.size(); i++) {
if (lastResult[i] != lastResult[i-1]) {
newResult += '0' + count;
newResult += lastResult[i-1];
count = 1;
} else {
count++;
}
if (i == lastResult.size() - 1) {
newResult += '0' + count;
newResult += lastResult[i];
}
}
}
return newResult;
}