Count and Say
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";
string s=countAndSay(n-1);
int count=1,say=s[0]-'0';
int m=s.length();
string res;
for(int i=1;i<m;i++){
if((s[i]-'0')!=say){
res+=count+'0';
res+=say+'0';
say=(s[i]-'0'),count=1;
}
else
count++;
}
res+=count+'0';
res+=say+'0';
return res;
}
};