leetcode 38. 报数 Count and Say

解法详见注释

python

class Solution:
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        s = '1'
        if n==1:
            return s
        else:
            for i in range(n-1):
                s = self.get_next(s)
            return s
    
    def get_next(self, s):
        ref_c = s[0]  #初始时以第0个字母为参考字母
        cnt = 1  #参考字母出现的次数
        res = ''  #保存结果
        for c in s[1:]:  #从第二个字母开始
            if c==ref_c:  #若该字母等于参考字母
                cnt+=1    #则次数+1
            else:
                res=res+str(cnt)+str(ref_c)  #否则说明连续相等的字母结束,生成报数结果
                ref_c = c  #更新参考字母为当前字母
                cnt = 1   #更新次数为1
        res=res+str(cnt)+str(ref_c)  #补充最后一个连续字母
        return res

猜你喜欢

转载自blog.csdn.net/yuejisuo1948/article/details/85244298