The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, …
1is read off as”one 1”or11.
11is read off as”two 1s”or21.
21is read off as”one 2, thenone 1”or1211.
Given an integer n, generate the n th sequence.
Note: The sequence of integers will be represented as a string.
class Solution {
public:
void count(string &s)
{
int n = s.size();
char last = s[0];
int cnt = 1;
string s1 = "";
for(int i=1; i<s.size(); i++)
{
if(last == s[i])
{
cnt++;
}
else
{
stringstream ss;
ss << cnt;
s1 = s1 + ss.str() + last;
cnt = 1;
last = s[i];
}
}
stringstream ss;
ss << cnt;
s1 = s1 + ss.str() + last;
s = s1;
}
string countAndSay(int n)
{
if(n <= 0)
return "";
string s = "1";
if(n == 1)
return s;
for(int i=2; i<=n; i++)
count(s);
return s;
}
};