工作生活

38. Count and Say

2019-07-04  本文已影响0人  poteman
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        if n == 1:
            return "1"
        res = ["1"]
        for i in range(1, n):
            tempres = ""
            cur = res[i-1]
            char = cur[0]
            cnt = 0
            for k in range(len(cur)):
                if cur[k] == char:
                    cnt += 1
                else:
                    tempres += str(cnt)
                    tempres += char
                    # 更新char,并设置cnt为1(已经被计数一次)
                    char = cur[k]
                    cnt = 1
            # 最后一个char还没被加到tempres中,记得加上
            tempres += str(cnt)
            tempres += char
            
            res.append(tempres)
        return res[-1]
上一篇 下一篇

猜你喜欢

热点阅读