leetcode笔记--Count and Say

题目:难度(Easy)

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.
Tags:String
Similar Problems:(M) Encode and Decode Strings

分析:开始我对这个题目的意思理解有错误,以为是给一个数字n,然后把它改写成count+数字这样的串,例如我以为输入11112223444时,那么输出就应该是41321334,即我以为就是按题意输出这个数字的”读法“,所以实现了这样一个函数:

    def readOff(self, n):
        #数字被表示成:个数+数
        nStr = str(n)
        #count用来计数,每个数字连续出现的次数
        count = 1
        i = 0
        result = []
        while i < len(nStr):
            if i < len(nStr) - 1:
                #i不指向最后一个数字字符
                if nStr[i] == nStr[i+1]:
                    count += 1
                else:
                    result.append(str(count))
                    result.append(nStr[i])
                    count = 1
                
            else:
                result.append(str(count))
                result.append(nStr[i])
                count = 1
            i += 1
        return "".join(result)
但提交时出错,testcase里输入为1时,输出为1并不是我的11(读作one 1),当输入为2时他的输出为11并不是我的12(读作one 2)

仔细分析题目,The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...即1,11,21,1211,是整数序列1,2,3,4。。。然后把数字的表示方法和对应的读法比对一下:

leetcode笔记--Count and Say_第1张图片

发现:一个数字的表示方法 是他前一个数字的读法

因此,只需利用前面已经实现的找数字的”读法“的函数就可以实现上述要求。明显这里对数字的表示方法的定义是一个递归的定义。第i个整数的表示方法总是基于第i-1个数字的”读法“(i>1),又已知第1个数表示为1,所以递归关系容易得出。

代码实现:

class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        if n == 1:
            return "1"
        else:
            return self.readOff(int(self.countAndSay(n-1)))
    
    def readOff(self, n):
        #数字被表示成:个数+数
        nStr = str(n)
        #count用来计数,每个数字连续出现的次数
        count = 1
        i = 0
        result = []
        while i < len(nStr):
            if i < len(nStr) - 1:
                #i不指向最后一个数字字符
                if nStr[i] == nStr[i+1]:
                    count += 1
                else:
                    result.append(str(count))
                    result.append(nStr[i])
                    count = 1
                
            else:
                result.append(str(count))
                result.append(nStr[i])
                count = 1
            i += 1
        return "".join(result)



你可能感兴趣的:(LeetCode,String,递归,encode)