一、题目
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
二、思路
首先题目有歧义,第一次做还意味是给出一个串“1211”,把它读出来。。。
提交了一次发现好奇怪的测试例,后来才发现是让给定n,返回第n个这样的序列。。
思路还算简单,用递归的方法产生。读一个,写到list中,再读刚刚写入的,如此循环。
在读的时候,就遍历,边界情况要处理一下。
有了上次的小技巧,想把for .. in 都写成[]的样子,还是用的不熟,最终作罢,一会儿看一下[]的语法
三、代码
class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ num = [‘1‘] for i in range(n): num.append(self.say(num[-1])) return num[-2] def say(self, n): lenN = len(n) if lenN == 0: return "" elif lenN == 1: return ‘1‘ + n[0] count = 1 rst = "" for cur in range(1, lenN): if n[cur] == n[cur - 1]: count += 1 if cur == len(n) - 1: rst += str(count) + n[cur] else: rst += str(count) + n[cur - 1] count = 1 if n[-1] != n[-2]: rst += ‘1‘ + n[-1] return rst else: return rst
四、感悟
1.列表包含
1)一般循环
nums = [i for i in range(5)] = [0,1,2,3,4]
square = [n * n for n in nums]
2)加判断
[expression for item1 in iter1 if condition1
for item2 in iter2 if condition2
...
for itemn in itern if conditionn]
等价于:
for item1 in iter1:
if condition1:
for item2 in iter2:
if condition2:
....
实例:
a = [-3, 4 ,5, -10]
b = "abc"
e = [(x, y) for x in a
for y in b
if x > 0]