LeetCode小白菜笔记[12]:Count and Say
LeetCode小白菜笔记[12]:Count and Say
38. count and say [easy]
题目如下:
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 *n*th term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"
题目的意思是,对于一个整数序列,每一个数字都是上面的一个count and say。所谓的 count and say 的意思就是说,对于上一个数字,如果有n个连续的数字m,那么下一个数字中就有一个连着的nm表示n个m,然后按顺序依次数完上面的数字。开始以为有规律,后来没有发现规律,放弃,让生成第n个,就需要从第一个开始,做n次这样的处理,得到第n个,code如下:
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n == 1:
return '1'
elif n == 2:
return '11'
elif n == 3:
return '21'
else:
last = self.countAndSay(n-1)
current = ''
count = 1
say = last[0]
for i in range(1,len(last)):
if last[i] == say:
count += 1
else:
current = current + str(count) + str(say)
say = last[i]
count = 1
current = current + str(count) + str(say)
return current
用了个递归,常规解法。为了写range(1,len(last))不报错,把前三项都做成了直接return。最后倒数第二行是因为最后的一组count and say只是数出来了,并未加到返回值里面。因为我们用后一项和前一项不相同作为分割符,然后扩充要返回的字符串,因此最后一组没有分隔符,因为后面没有了,所以要单独加上。
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n == 1:
return '1'
else:
last = self.countAndSay(n-1)
current = ''
count = 1
say = 0
for i in range(len(last)):
if last[i] == say:
count += 1
else:
if not say == 0:
current = current + str(count) + str(say)
say = last[i]
count = 1
current = current + str(count) + str(say)
return current
上面的elif语句太多,不好看,所以改了一下,这样就只需要一个直接return的,其余都通过递归。
2018年2月8日23:02:09
放假回家第一天~加油加油~