题目解析:给定一个整型数n,要求按规律的第n个string。规律如下:
n=1 string = "1";
n=2 string = "11"; //1个1
n=2 string = "21"; //2个1
n=4 string = "1211"; //1个2,1个1
n=5 string = "111221"; //1个1,1个2,2个1
n=6 string = "312211"; //3个1,2个2,1个1
以此类推,求第n个字符串string。
解题思路就是,从第一个string依次写,一直写到第n个string。第n个string就是对第n-1个string依次数它字符的数目,保存即可。
我的答案:
class Solution {
public:
string countAndSay(int n) {
string present, next;
char ch;
int num=0,i;
present.push_back('1'); // 当前字符串为"1"
while(--n){
ch = present[0];
next.clear();
for(i=0;i<present.size();++i){
if(present[i]==ch) //计数字符的数目
++num;
else{
next.push_back('0'+num); //字符表示数字的时候要用'0'+ (int)num
next.push_back(present[i-1]);
num = 1;
ch = present[i];
}
}
next.push_back('0'+num);
next.push_back(present[i-1]);
present.clear();
present = next;
num = 0;
}
return present;
}
};