星空网 > 软件开发 > 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 }

 




原标题:38. Count and Say

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

正宗德国好博的标志怎么区分:https://www.goluckyvip.com/tag/59908.html
非接触式支付:https://www.goluckyvip.com/tag/5991.html
纳粹德国的标志:https://www.goluckyvip.com/tag/59915.html
二战德国的标志:https://www.goluckyvip.com/tag/59920.html
德国大众车标:https://www.goluckyvip.com/tag/59921.html
纳粹德国标志:https://www.goluckyvip.com/tag/59925.html
武陵山大裂谷周围景点 武陵山大裂谷周围景点图片:https://www.vstour.cn/a/411233.html
南美旅游报价(探索南美洲的旅行费用):https://www.vstour.cn/a/411234.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流