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;
}
C++ solution easyunderstand


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(n1); string newresult = ""; int count = 1; for(int i = 1; i < result.size(); ++i){ if(result[i]!=result[i1]){ newresult.push_back('0'+count); newresult.push_back(result[i1]); count = 1; }else{ count++; } if(i == result.size()1){ newresult.push_back('0'+count); newresult.push_back(result[i]); } } return newresult; }
};

@Leila_ECE said in C++ solution easyunderstand:
count
How to prove the "count" here won't be greater than 10?


@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.