题目:
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 str = "1";
if(n == 1)
return str;
n = n - 1;
while(n--)
{
string tmp = "";
int len = str.length();
int cnt = 1;
char s = str[0];
for(int i = 1;i < len; ++i)
{
if(s == str[i])
cnt++;
else
{
tmp += ('0' + cnt);
tmp += s;
s = str[i];
cnt = 1;
}
}
tmp += ('0' + cnt);
tmp += s;
str = tmp;
}
return str;
}
};