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) {
string s=this->itoa(1);//第一个
for(int i=2;i<=n;++i){//从第二个开始
s = nextNum(s);
}
return s;
}
private:
string itoa(int i){
char buf[10];
memset(buf,0,sizeof(buf));
sprintf(buf,"%d",i);
string s(buf);
return s;
}
string nextNum(string &s){
string res;
int j=1,count =1;
for(;j<s.size();++j){
if(s[j] == s[j-1]) ++count;
else{
res.push_back('0'+count);
res.push_back(s[j-1]);
count=1;
}
}
res.push_back('0'+count);
res.push_back(s[j-1]);
return res;
}
};