报数

99 阅读1分钟

报数

public class Solution {
    /**
     * @param n: the nth
     * @return: the nth sequence
     */
    public String countAndSay(int n) {
        // write your code here
        String start = "1";
        int index = 1;
        while(index < n){
            StringBuilder temp = new StringBuilder();
            for(int i = 0; i < start.length(); i++){
                char c = start.charAt(i);
                if(i + 1 < start.length()){
                    if(c == start.charAt(i + 1)){
                        int num = 1;
                        int k = i;
                        for(int j = k + 1; j < start.length(); j++){
                            if(start.charAt(j) == c){
                                num++;
                                i++;
                            }else{
                                break;
                            }
                        }
                        temp.append(num + ""+ c);
                    }else{
                        temp.append("1" + c);
                    }
                }else{
                    temp.append("1" + c);
                }
            }
            start = temp.toString();
            index++;
        } 
        return start;
    }
}

报数指的是,按照其中的整数的顺序进行报数,然后得到下一个数。如下所示:

1, 11, 21, 1211, 111221, ...

1 读作 "one 1" -> 11.

11 读作 "two 1s" -> 21.

21 读作 "one 2, then one 1" -> 1211.

给定一个整数 n, 返回 第 n 个顺序。

解题思路

通过循环遍历找相同的数