【LeetCode题意分析&解答】38. 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开始,将当前数字转化为口语对应的数字。比如1口语是1个1,记作11;11读作2个1,记作21;21读作1个2,1个1,记作1211……

  '1'是第一个数字,根据输入的数字n,计算第n个这样的数字。

  说起来比较拗口,对照着例子可以感受一下……

解答:

  如果你理解题意,那么解答就很简单。直接循环,每个数字按照题目要求翻译成口语对应的数字,按照顺序找到第n个返回就行了。

  Leetcode给的评级是Easy,这是对于程序难度来说,然而对于题意来说容易理解偏。

AC代码:

class Solution(object):
    def countAndSay(self, n):
        if n < 2: return '1'
        ret_str = '1'
        while n > 1:
            temp, current_num = '', 0
            for i, v in enumerate(ret_str):
                if i > 0 and v != ret_str[i - 1]:
                    temp += str(current_num) + ret_str[i - 1]
                    current_num = 1
                else:
                    current_num += 1
            ret_str = temp + (str(current_num) + ret_str[-1] if current_num != 0 else '')
            n -= 1
        return ret_str

后话:   

  其实这道题有个很有意思的地方,即输出的数字中永远不可能有大于3的数字,只会出现1、2、3三个数字,你能够证明吗?

原文地址:https://www.cnblogs.com/zhuifengjingling/p/5285758.html