lintcode python代码 420 报数

来源:互联网 发布:单片机仿真软件程序 编辑:程序博客网 时间:2024/05/25 19:57

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

1, 11, 21, 1211, 111221, …

1 读作 “one 1” -> 11.

11 读作 “two 1s” -> 21.

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

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

思路:数字不好处理位数,将其变为字符串。从后往前读,记最后一个temp = string[-1],相同+1。不同result = str(count) + temp + result temp = string[i] count = 1

class Solution:    # @param {int} n the nth    # @return {string} the nth sequence    def countAndSay(self, n):        # Write your code here        string = '1'        for _ in range(n-1):            count = 0            temp = string[-1]            result = ''            for i in range(len(string)-1, -1, -1):                if temp == string[i]:                    count += 1                else:                    result = str(count) + temp + result                    temp = string[i]                    count = 1            string = str(count) + temp + result        return string
原创粉丝点击