使用模拟法:
#include <iostream>
using namespace std;
class Solution {
public:
string countAndSay(int n) {
if (n==1) {
return "1";
}
string preStr="1";
string nextStr="";
int count=0;
for (int i=2; i<=n; i++) {
int j=0;
while (j<preStr.length()) {//注意此处使用while;因为步长不定,不适用for
char key=preStr[j];
while (j<preStr.length()&&key==preStr[j]) {//注意此处使用while;if为条件选择,无循环功能
count++;
j++;
}
//cout<<count<<":"<<key<<endl;
nextStr+=count+'0';//转字符
nextStr+=key;
//cout<<nextStr<<endl;
count=0;
}
preStr=nextStr;
//cout<<"preStr is "<<preStr<<endl;//注释掉,否则会报Output Limit Exceeded
nextStr="";
}
return preStr;
}
};
int main(int argc, const char * argv[])
{
Solution so;
//so.countAndSay(1);
string res=so.countAndSay(7);
cout<<"the result is "<<res<<endl;
return 0;
}