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.
此题难以程度为easy,只需要按照题目规律一直推算到第n项即可。
class Solution {
public:
string countAndSay(int n) {
string str("1");
string res;
char cur='0';
char count='0';
while(n>1)
{
for(int i=0;i<str.size();i++)
{
if(cur=='0') cur=str[i];
if(cur!=str[i])
{
res.push_back(count);
res.push_back(cur);
count='0';
cur=str[i];
}
if(cur==str[i])
count=count+1;
}
res.push_back(count);
res.push_back(cur);
str=res;
res="";
count='0';
cur='0';
n--;
}
return str;
}
};