1.(字符串)-计算n个数count-and-say

如: 

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.

python:


def countAndSay(n):
    if n == 0:
        return ''
    res = '1'
    while n != 0:
        n -= 1
        print(res)
        i = 0
        count = 1
        cur = ''
        # 拼接res的读数
        while i < len(res):
            count = 1
            while i + 1 < len(res) and res[i] == res[i + 1]:
                count += 1
                i += 1
            #     数量+本身
            cur += str(count) + res[i]
            # 到下一个数字位
            i += 1
        res = cur
    return res


s = countAndSay(5)

#output

1
11
21
1211
111221

posted @ 2019-02-12 22:03  jj千寻  阅读(133)  评论(0编辑  收藏  举报