题目:2
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.
解法:模拟。。1Y又失败。。
class Solution
{
public:
string int_to_string(int t)
{
std::stringstream newstr;
newstr<<t;
return newstr.str();
}
string countAndSay(int n)
{
if(n<=0) return "";
string s = "1";
while(--n)
{
string t = "";
while(s.size()>0)
{
int cnt=-1;
for(int i=0;i<s.size();i++)
{
if(s[i]!=s[0]) {cnt=i;break;}
}
if(cnt == -1)
{
cnt = s.size();
}
t=t+int_to_string(cnt)+s[0];
s=s.substr(cnt,s.size()-cnt);
}
s=t;
}
return s;
}
};