个人思路总结:
这个题最大的难度可能是读懂题目吧。。。
题意大概为:其实就是个读数问题,如第5个是"111221" 那么第6个就是读第5个中的数字“3个1,2个2,1个1”即为“312211” 第7个读第6个数为“1个3,1个1,2个2,2个1”即为“13112221” 以此类推。
然后从1开始依次循环即可。
代码如下:
class Solution {
public:
string countAndSay(int n) {
string s0 = "1";
string s1 = "";
int i = 1;
while(i++<n){
s0 += "0";
int count = 1;
for(int j = 0; j < s0.size()-1; j++){
if(s0[j] == s0[j+1]) count++;
else{
s1 += to_string(count);
s1 += s0[j];
count = 1;
}
}
s0 = s1;
s1.clear(); //用clear清除字符串要比赋空字符串快。
}
return s0;
}
};