一、 题目
题目说,如下的字符串:
1, 11, 21, 1211, 111221, ...
1读成11(一个1)
11读成21(两个1)
21读成(一个2一个1)
......
给一个整数,返回对应得语句。返回语句为一个字符串
二、 分析
题目的意思不是很明白,其实就是说第i+1个字符串是第i个字符串的读法,第一字符串为 “1”
比如第四个字符串是1211,它的读法是 1个1、1个2,2个1,因此第五个字符串是111221。第五个字符串的读法是:3个1、2个2、1个1,因此第六个字符串是312211。
明白了题意,我们不难想到思路:
1、初始字符串为”1”,字符ch为 str[0],中间字符串为str2;
2、从1开始循环产生字符串直到n;
3、遍历字符串,计数相连的相同字符,并产生新的字符串;
class Solution {
public:
string countAndSay(int n) {
if(n == 0)
return "";
string str = "1";
for(int i = 1; i < n; i++){
char ch = str[0];
string str2 = "";
int count = 1;
for(int j=1;j<str.size();j++){
if (str[j] == ch)
count ++;
else if(count > 0){
str2 = str2 + char(count + '0') + ch;
count = 1;
ch = str[j];
}
}
str2 = str2 + char(count + '0') + ch;
str = str2;
}
return str;
}
};