leetcode38. Exterior columns

"Appearance number of columns" is a sequence of integers, beginning with the number 1, is the description of the preceding each item in the sequence. The first five are as follows:

1.1
2.11
3.21
4.1211
5.111221
1 is read as "one 1" ( "a a"), i.e., 11.
11 is read as "two 1s" ( "two one"), i.e., 21.
21 is read as "one 2", "one 1 " ( " a two", "a a"), i.e., 1211.

Given a positive integer n (1 ≤ n ≤ 30), the n-th series term output appearance.

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

 

Example 1:

Input: 1
Output: "1"
Explanation: This is a basic sample.
Example 2:

Input: 4
Output: "1211"
Explanation: When n = 3, the sequence is "21", which we have "2" and "1" groups, "2" can be read as "12", i.e. occurrence frequency = = 1 and the value 2; similarly "1" can be read as "11." So the answer is "12" and "11" are combined, that is, "1211."

 Ideas: difficulty in understanding the problem it possible, after understanding can be simulated. See in particular code.

class Solution {
    /**
     * 难点:报数的概念理解
     * 从4->5分析,将4个每一位拆开看(个数+数字),4=1211 => 1=11,2=12,11=21,所以5=111221
     * 模拟出来过程即可
     */
    public String countAndSay(int n) {
        String str = "1";
        for (int i = 2; i <= n; i++) {
            StringBuilder builder = new StringBuilder();
            char pre = str.charAt(0);
            int count = 1;
            for (int j = 1; j < str.length(); j++) {
                char c = str.charAt(j);
                if (c == pre) {
                    count++;
                } else {
                    builder.append(count).append(pre);
                    pre = c;
                    count = 1;
                }
            }
            builder.append(count).append(pre);
            str = builder.toString();
        }
        return str;
    }
}

 

Published 446 original articles · won praise 6751 · Views 1.02 million +

Guess you like

Origin blog.csdn.net/hebtu666/article/details/104060737