(leetCode)Count and Say --- 统计读

来源:互联网 发布:32bit安装tensorflow 编辑:程序博客网 时间:2024/04/30 08:52

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.

Subscribe to see which companies asked this question


解题分析:

对于这种题目,首先看清题意,解决方法就是分别读取每个字符出现的个数,存储就可以了。



# -*- coding:utf-8 -*-__author__ = 'jiuzhang'class Solution(object):    def countAndSay(self, n):        seq = ['1']        top = 1        while n - 1 > 0:            n -= 1            bak = []            i = 0            while i < top:                num = 1                while i + 1 < top and seq[i+1] == seq[i]:                    i += 1                    num += 1                bak.append(chr(num + ord('0')))                bak.append(seq[i])                i += 1            seq = bak            top = len(bak)        return ''.join(seq)


0 0
原创粉丝点击