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.
这个题目的意思我觉得挺难理解的,看了好久,才知道是什么意思。
主要意思就是计算上一个序列的数每一位上数的个数。
比如111221,它依次就是3个1,2个2,1个1
下一个序列就是312211.
class Solution {
public:
string countAndSay(int n) {
if (n == 1) {
return "1";
} else {
string s = countAndSay(n - 1);
string ans="";
int count=1;
for(int i=0;i<s.size();i++){
if(s[i]==s[i+1]){
count++;
}else
{
char c=count+'0';
ans=ans+c;
ans=ans+s[i];
count=1;
}
}
return ans;
}
}
};