您的位置:首页 > 其它

leetcode-Count and Say

2014-05-26 21:39 337 查看
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.

思路:递归

代码:

string countAndSay(int n) {

    string res;

if(n<1)
return NULL;
else if(n == 1)
{
res="1";
return res;
}
else if(n == 2)
{
return "11";
}
int lenOfRes=0;
string s=countAndSay(n-1);
int len=s.length();
int count=1;
char temp;

int i=0;
for(i=0; i<len-1; ++i)
{
if(s[i] == s[i+1])
{
count++;
}
else
{
   temp=count+48;
res+=temp;
res+=s[i];
count=1;
}
}
if(s[i-1] == s[i])
{
   temp=count+48;
res+=temp;
res+=s[i];
}

if(s[i-1] != s[i])
{
   temp=49;
res+=temp;
res+=s[i];
}

return res;

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: