你的位置:首页 > Java教程

[Java教程]38. Count and Say


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.

代码如下:

方法一:

 1 public class Solution { 2   public String countAndSay(int n) { 3     4       String s="1"; 5       if(n==0||n==1) 6         return s; 7          8       String result=""; 9       for(int k=1;k<n;k++) //用for循环10       {11         12         char[] ss=s.toCharArray();13         14         result="";15         int i=0;16         int j=0;17 18         for( i=0;i<ss.length;)19         {20           char a=ss[i];21           int count=0;22           for(j=i;j<ss.length;j++)23           {24             if(a==ss[j])25               count++;26             else break;27           }28           result=result+Integer.toString(count)+Character.toString(a);29 30           i=j;31         }32 33         s=result;34           }35 36     return s;37   }38 }

 

方法二:

 1 public class Solution { 2   public String countAndSay(int n) { 3     4       String s="1"; 5       if(n==0||n==1) 6         return s; 7        8       s=countAndSay(n-1);//用递归 9       String result="";10 11         char[] ss=s.toCharArray();12         result="";13         int i=0;14         int j=0;15 16         for( i=0;i<ss.length;)17         {18           char a=ss[i];19           int count=0;20           for(j=i;j<ss.length;j++)21           {22             if(a==ss[j])23               count++;24             else break;25           }26           result=result+Integer.toString(count)+Character.toString(a);27 28           i=j;29         }30 31     return result;32   }33 }