Count and Say

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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 sequence.

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

一道很有意思的题目,第一个状态为1,第二个状态为11(一个1),第三个状态为21(两个1),第四个状态为1211(一个2和一个1),第五个状态为111221(一个1,一个2,两个1),. . .,让我们找到第n个状态。我们可以从第一个状态开始处理,一直衍生到第n个状态。当然状态衍生下一代时,我们从第一个数子开始比较,用一个计数counter来记录相同数字的个数,遇到不同的就讲当然counter的值和当然数字加入到字符串中,同时将counter置1,这样一直遍历完当前的状态,从而得到下一个状态。代码如下:
public class Solution {
    public String countAndSay(int n) {
        if(n <= 0) return "";
        String result = "1";
        int i = 1;
        while(i < n) {
            StringBuilder sb = new StringBuilder();
            int count = 1;
            for(int j = 1; j < result.length(); j++) {
                if(result.charAt(j) == result.charAt(j - 1)) {
                    count ++;
                } else {
                    sb.append(count);
                    sb.append(result.charAt(j - 1));
                    count = 1;
                }
            }
            sb.append(count);
            sb.append(result.charAt(result.length() - 1));
            result = sb.toString();
            i ++;
        }
        return result;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2274443