LeetCode 38. 报数

报数序列是指一个整照其中的整数的顺序进数序列,按行报数,得到下一个数。其前五项如下:

1.     1
2.     11
3.     21
4.     1211
5.     111221

1 被读作  "one 1"  ("一个一") , 即 11
11 被读作 "two 1s" ("两个一"), 即 21
21 被读作 "one 2",  "one 1" ("一个二" ,  "一个一") , 即 1211

给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。

注意:整数顺序将表示为一个字符串。

 

示例 1:

输入: 1
输出: "1"

示例 2:

输入: 4
输出: "1211"

public static String countAndSay(int n) {
        String initialString = "1";// 第一次从"1"开始
        for (int i=1; i<n; i++) {
            // 定义StringBuffer接收报数后的结果
            StringBuffer stringBuffer = new StringBuffer();
            String[] strings = initialString.split("");
            // 定义count接收相同字符的个数
            int count = 1;
            /**
             * 对相同的字符进行计数,如果相同,则count自增
             * 如果与后一个字符不同,则将个数与字符添加到StringBuffer(相当于"几个几")
             * 然后将count重新赋值为1,继续进行下一个字符的计数
             */
            for (int j=0; j<strings.length; j++) {
                if (j == strings.length-1 || !strings[j].equals(strings[j+1])) {
                    stringBuffer.append(count+strings[j]);
                    count = 1;
                    continue;
                }
                if (strings[j].equals(strings[j+1])) {
                    count++;
                }
            }
            initialString = stringBuffer.toString();
        }
        return initialString;
    }

 

posted @ 2018-10-03 17:34  Narcissus94  阅读(89)  评论(0编辑  收藏  举报