• 题目要求:

image.png

  • 思路:

    • 遍历字符串,用res来保存最终返回的结果,count记录当前字符出现的次数,如果当前的字符与下一个字符相同,那么count加一,如果不同,把str(count)和当前字符记录到res中。
  • 核心代码:
#起始的字符串为"1",因为n在1到30之间,所以不用判断0的情况
res = "1"
#循环n-1次
for i in range(n-1):
    res = self.getNext(res)
return res


def getNext(self,res):
    #index为当前遍历到的字符的下标,next_seq是下一个字符串
    index , next_seq = 0 , ""
    
    while index < len(res):
        #第一次出现的次数就为1,所以count起始为1
        count = 1
        # 当前的字符与下一个字符相同,而且下标没有超过字符串长度减一时
        while index < len(res) - 1 and res[index] == res[index+1]:
            count += 1
            index += 1
        #如果当前字符与下一个字符不同,把当前的字符出现的次数与当前的字符加到要返回的字符串里
        next_seq += str(count) + res[index]
        #下标加一,继续遍历
        index += 1
        
    return next_seq
  • 完整代码:
class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        res = "1"
        for i in range(n-1):
            res = self.getNext(res)
        return res


    def getNext(self,res):
        index , next_seq = 0 , ""
        while index < len(res):
            count = 1
            while index < len(res) - 1 and res[index] == res[index+1]:
                count += 1
                index += 1
            next_seq += str(count) + res[index]
            index += 1
            
        return next_seq

Adrianna
1 声望2 粉丝