您的位置:首页 > 编程语言 > Python开发

【LeetCode 38】Count and Say(Python)

2018-01-08 15:08 337 查看
The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     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 term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.
题目分析:

分析给定数组的规律,根据输入的行数,输出所在行的具体内容。

给定数据的规律为:第一行--1;之后每一行的内容为上一行的数字串从左到右读出来。

第二行---一个‘1’ -----11

第三行---两个‘1’----21

第四行---一个‘2’一个‘1’----1211

。。。 。。。

示例:

Input:4                        Output:1211

方法一:

思路:由于每一行的内容为前一行的内容从左到右顺序读出,而且需要统计每个数字出现的次数。(此处有一点需要注意:相邻两个数字一样,累加统计。)所以要都读出的内容必须是字符型(char),不能是数字类型(int,float等)否则无法进行统计数字出现次数。 
 通过循环来进行统计读出。
我觉得此题的解体关键主要就是想清楚要将数组内容转换成字符型。
代码:
class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
b='1'   #将第一行的1换成字符类型,便于下一行的读出
for i in range (n-1):    #(n-1)是因为第一行不需要处理,直接可以读出
a,c,count=b[0],'',0   #a用来读取上一行的第一个字符,c用来存放读出的内容(char),count用来统计
for j in b:
if a==j:
count+=1
else:
c+=str(count)+a   #注意一定要将count转换为字符型,否则两个数就会相加(变成数学公式)。
a=j
count=1
c+=str(count)+a
b=c
return b
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: