1 题目

报数

2 解

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
    /** 编译正则,按照重复的数字分组 */
    private Pattern pattern = Pattern.compile("(\\d)\\1*");
    public String countAndSay(int n) {
        if (n == 1) return "1";
        StringBuilder result = new StringBuilder();
        result.append("1");
        for (int i = 1; i < n; i++){
            Matcher matcher = pattern.matcher(result);
            result = new StringBuilder();
            // 找出数字相同的分组,然后循环
            while(matcher.find()) {
                String group = matcher.group();
                char[] chars = group.toCharArray();
                // 先读数组长度,再读数组第一个数字即可
                result.append(chars.length).append(chars[0]);
            }
        }
        return result.toString();
    }
}