leetcode-Count and Say
2014-05-26 21:39
337 查看
The count-and-say sequence is the sequence of integers beginning as follows:
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;
}
1, 11, 21, 1211, 111221, ...
1is read off as
"one 1"or
11.
11is read off as
"two 1s"or
21.
21is 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;
}
相关文章推荐
- Leetcode: Count and Say
- LeetCode--Count and Say(Python)
- [LeetCode] Count and Say, Solution
- 【LeetCode38】【Count and Say】StringBuilder
- leetcode 64: Count and Say
- LeetCode - Count and Say
- 【LeetCode】Count and Say 解题报告
- LeetCode Count and Say
- 【leetcode】【38】Count and Say
- Leetcode 之Count and Say(35)
- LeetCode(51)- Count and Say
- [LeetCode] Count and Say
- (leetCode)Count and Say --- 统计读
- [LeetCode]Count and Say
- LeetCode_Count and Say
- 【Leetcode】之Count and Say
- LeetCode--Count and Say
- Leetcode 模拟 Count and Say
- 【LeetCode】Count and Say
- 【leetcode】Count and Say