The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1
is read off as "one
1"
or 11
.
11
is read off as "two
1s"
or 21
.
21
is read off as "one
2
, then one 1"
or 1211
.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
1. 1
2. 11
3. 21
4. 1211
5. 111221
6. 312211
7. 13112221
8. 1113213211
9. 31131211131221
10. 13211311123113112211
class Solution {
public:
string countAndSay(int n) {
if(n == 0) return "";
int cnt = 1;
string res = "1";
while(--n){
string cur = "";
int x = res.size();
for(int i = 0; i < x; ++i){
if(i < x-1 && res[i] == res[i+1])
cnt++;
else{
cur += to_string(cnt);
cur += res[i];
cnt = 1;
}
}
res = cur;
}
return res;
}
};