# C++ solution easy-understand

• ``````string countAndSay(int n) {
if (n == 0) return "";
string res = "1";
while (--n) {
string cur = "";
for (int i = 0; i < res.size(); i++) {
int count = 1;
while ((i + 1 < res.size()) && (res[i] == res[i + 1])){
count++;
i++;
}
cur += to_string(count) + res[i];
}
res = cur;
}
return res;
}``````

• This is my C++ solution with 0ms.
class Solution {

public:

``````string countAndSay(int n) {
if (n == 1){return "1";}
if (n == 2){return "11";}
string result = countAndSay(n-1);
string newresult = "";
int count = 1;
for(int i = 1; i < result.size(); ++i){
if(result[i]!=result[i-1]){
newresult.push_back('0'+count);
newresult.push_back(result[i-1]);
count = 1;
}else{
count++;
}
if(i == result.size()-1){
newresult.push_back('0'+count);
newresult.push_back(result[i]);
}
}
return newresult;
}
``````

};

• Good job!when i meet this problem, my first idea is to find the rule of replace ,but failed.Just follow the question and get the answer!

• count

How to prove the "count" here won't be greater than 10?

• @aceorochi good question

• @aceorochi When I run the sequence out, it doesn't even go above 3.
To get a 3, you need a sequence of something like 1113, which meant the previous sequence was 13.
To get a 4, the previous sequence had to be 1111, 2222, etc. But such a sequence cannot happen because 1111 or 2222's predecessor had to be 11 or 22, which would've compressed to 21 and 22.

This is not a rigorous proof but hopefully it makes sense.

• whats the complexity of this sol ?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.