lintcode :Count and Say 报数

题目:

报数

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

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

1 读作 "one 1" -> 11.

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

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

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

样例

给定 n = 5, 返回 "111221".

注意

整数的顺序将表示为一个字符串

解题:

题目思路很清晰,按照高位到低位的顺序,统计相同数字的个数,并把a个b写成ab的形式,所以的连接在一起就是一个新数,下一个数利用同样的规律。

一个有意思的网站,Python程序来源。

Java程序:

public class Solution {
    /**
     * @param n the nth
     * @return the nth sequence
     */
    public String countAndSay(int n) {
        // Write your code here
        String oldString = "1";
        while (--n>0){
            StringBuilder sb = new StringBuilder();
            char[] oldChars = oldString.toCharArray();
            for(int i=0;i<oldChars.length;i++){
                int count = 1;
                while((i+1)<oldChars.length && oldChars[i]==oldChars[i+1]){
                    count++;
                    i++;
                }
                sb.append(String.valueOf(count) + String.valueOf(oldChars[i]));
            }
            oldString = sb.toString();
        }
        return oldString;
        
    }
View Code

总耗时: 7304 ms

程序来源

Python程序:

class Solution:
    # @param {int} n the nth
    # @return {string} the nth sequence
    def countAndSay(self, n):
        # Write your code here
        p = '1'
        seq = [1]
        m = n 
        while n>1:
            q = ''
            idx = 0 
            l = len(p)
            while idx<l:
                start = idx 
                idx = idx + 1
                while idx<l and p[idx]==p[start]:
                    idx = idx + 1
                q = q+str(idx - start) + p[start]
            n, p = n -1 ,q 
            seq.append(int(p))
        return str(seq[m-1])
View Code

总耗时: 312 ms

根据运行错误的结果,发现这个题目的测试数据只是 1 到9 这9个数,太小了吧。。。

原文地址:https://www.cnblogs.com/bbbblog/p/4878457.html