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.
[Solution]
说明:版权所有,转载请注明出处。 Coder007的博客class Solution {
public:
string countAndSay(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
// invalid n
if(n <= 0)return "";
// generate result
string str = "1";
string tmp = "";
while(--n){
int cnt = 1, i = 1;
char ch = str[0];
// count and say
tmp = "";
while(i < str.size()){
if(str[i] == ch){
cnt++;
}
else{
// add cnt and ch
char head[3];
head[0] = cnt + '0';
head[1] = ch;
head[2] = '\0';
tmp += string(head);
// update cnt and ch
cnt = 1;
ch = str[i];
}
i++;
}
// be careful the last one
if(cnt > 0){
// add cnt and ch
char head[3];
head[0] = cnt + '0';
head[1] = ch;
head[2] = '\0';
tmp += string(head);
}
// update str
str = tmp;
}
return str;
}
};