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.
没看答案独立完成的第一道题,mark……
class Solution {
public:
string countAndSay(int n) {
string s,ts;
int num,i,si,sn;
char c1,c2;
s='1';
if(n==1)
return s;
i=1;
while(i<n)
{
si=0;
ts="";
while(si<s.length())
{
sn=1;
switch(s[si])
{
case '1':c2='1';break;
case '2':c2='2';break;
case '3':c2='3';break;
case '4':c2='4';break;
case '5':c2='5';break;
case '6':c2='6';break;
case '7':c2='7';break;
case '8':c2='8';break;
case '9':c2='9';break;
}
while((si<s.length()-1)&&(s[si]==s[si+1]))
{
sn++;si++;
}
switch(sn)
{
case 1:c1='1';break;
case 2:c1='2';break;
case 3:c1='3';break;
case 4:c1='4';break;
case 5:c1='5';break;
case 6:c1='6';break;
case 7:c1='7';break;
case 8:c1='8';break;
case 9:c1='9';break;
}
ts=ts+c1+c2;
si++;
}
i++;
s=ts;
}
return s;
}
};