count-and-say

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     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 term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: "1"

 

Example 2:

Input: 4
Output: "1211"

 

题目解析:按照上面所述规则输出第n个数。我们发现,第n个数和第n-1个数之间的关系:从前往后依次统计第n-1个字符串的字符个数,连续出现a个字符x,就在第n个字符串后面添加"ax"。如1211,一个1,一个2,两个1,所以依次添加到第n个字符串中为11 12 21(中间本没有空格,这里是方便理解加了空格)。

对于这种后一个与前一个有联系的,我们可以使用递归。递归清楚容易理解,而且也快

递归代码:

class Solution {
    public String countAndSay(int n) {
       if(n==0)
                return null;
            if(n==1)
                return "1";
            else{
                String s=countAndSay(n-1);
          //通过第n-1个开始计算第n个。 StringBuilder sb
=new StringBuilder(); char[] c=s.toCharArray(); int count=1;
          //用一个计数器表示当前字母连续出现的次数,将次数和字符加入到字符串后面
for(int i=1;i<c.length;i++){ if(c[i]==c[i-1]) count++; else{ sb.append(count).append(c[i-1]); count=1;//重新计算下一个连续字符 } }
          //上面操作是进行到最后一个字符跟倒数第二个比较,并没有将最后一个字符加入到字符串中。 sb.append(count).append(c[c.length
-1]); return sb.toString(); } } }

 

当然,也可以不使用递归,就进行n此操作,从第一个到第n个。跟上面递归关键地方差不多,只不过这里是循环

public String countAndSay(int n) {
    if(n==1) return "1";
    
    String res = "1";
  //n-1此循环
for(int i=2; i<=n; i++) { res = helper(res); } return res; } 这个方法就是根据上一个字符串,得到该字符串并返回 public String helper(String str) { int count = 1; String res = ""; for(int i=1; i<str.length(); i++) { if(str.charAt(i) == str.charAt(i-1) ) count++; else { res += ((Integer)count).toString() + str.charAt(i-1); count = 1; } } res += count + str.substring(str.length()-1, str.length()); return res; }

 

posted on 2017-12-19 14:55  夜的第八章  阅读(449)  评论(0编辑  收藏  举报

导航