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.
class Solution {
public:
string countAndSay(int n) {
if(n==1) return "1"; // base case
string res,tmp = countAndSay(n-1); // recursion
char c= tmp[0];
int count=1;
for(int i=1;i<tmp.size();i++)
if(tmp[i]==c)
count++;
else {
res+=to_string(count);
res.push_back(c); //res.push_back(c)的效果就是字符串拼接,相当于 res+=c ,两条语句合并可写为:res=res+to_string(count)+c;
c=tmp[i];
count=1;
}
res+=to_string(count);
res.push_back(c);
return res;
}
};