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.
代码如下:
方法一:
public class Solution {
public String countAndSay(int n) { String s="1";
if(n==0||n==1)
return s; String result="";
for(int k=1;k<n;k++) //用for循环
{ char[] ss=s.toCharArray(); result="";
int i=0;
int j=0; for( i=0;i<ss.length;)
{
char a=ss[i];
int count=0;
for(j=i;j<ss.length;j++)
{
if(a==ss[j])
count++;
else break;
}
result=result+Integer.toString(count)+Character.toString(a); i=j;
} s=result;
} return s;
}
}
方法二:
public class Solution {
public String countAndSay(int n) { String s="1";
if(n==0||n==1)
return s; s=countAndSay(n-1);//用递归
String result=""; char[] ss=s.toCharArray();
result="";
int i=0;
int j=0; for( i=0;i<ss.length;)
{
char a=ss[i];
int count=0;
for(j=i;j<ss.length;j++)
{
if(a==ss[j])
count++;
else break;
}
result=result+Integer.toString(count)+Character.toString(a); i=j;
} return result;
}
}