flowingfog

偶尔刷题

  博客园  :: 首页  :: 新随笔  :: 联系 ::  :: 管理

分析

难度 易

来源

https://leetcode.com/problems/count-and-say/description/

题目

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 where 1 ≤ n ≤ 30, 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"
解答
 1 package LeetCode;
 2 
 3 public class L38_CountAndSay {
 4     public String countAndSay(int n) {
 5         if(n<=0){
 6             return null;
 7         }
 8         String res="1";//第一行结果
 9         int len = 0;
10         for(int i=1;i<n;i++){//第二行及以后
11             int count=1;//数字出现次数
12             if(i==1){//第二行
13                 res="11";
14             }else {//不加else的计划,第二行有res,还会接着构建,第二行的res就会成为原本第三行展示的内容
15                 len = res.length();
16                 StringBuilder sb = new StringBuilder();
17                 for (int j = 1; j < len; j++) {//统计每个字符出现次数
18                     if (res.charAt(j - 1) == res.charAt(j)) {
19                         count++;
20                     } else {
21                         sb.append(count);
22                         sb.append(res.charAt(j - 1));
23                         count = 1;
24                     }
25                 }
26                 sb.append(count);
27                 sb.append(res.charAt(len - 1));
28                 res = sb.toString();
29             }
30         }
31         return res;
32     }
33     public static void main(String[] args){
34         L38_CountAndSay l38=new L38_CountAndSay();
35         System.out.println(l38.countAndSay(4));
36     }
37 } 
posted on 2018-10-16 19:22  flowingfog  阅读(189)  评论(0编辑  收藏  举报