此题简单的模拟就行了。以后做题的适合,一定要想明白再写代码。代码如下:
class Solution {
public:
string countAndSay(int n) {
string res = "1";
int i = 1;
while (i<n) {
string next;
int count = 1;
for (int j = 1; j <(int)res.length(); j++) {
if (res[j] == res[j-1]) {
count++;
} else {
next += to_string(count) +res[j-1]; // 注意res[j-1]是char类型以及to_string函数的使用
count = 1;
}
}
next += to_string(count) +res[res.length()-1]; // 结尾数字不要忘记加上
res = next;
i++;
}
return res;
}
};