Leetcode 38题 Count and Say
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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Explanation: This is the base case.
Example 2:
Input: 4
Output: "1211"
Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211".
题目大意:
说实话,这道理的题目叙述的不好。读懂题是第一个难点。
题目对应的中文意思是“计数和发言”
题意是n=1时输出字符串1;n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;n=3时,由于上次字符是11,有2个1,所以输出21;n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。以此类推
按照规则写即可。
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
res = '1'
for i in range(n-1):
new_res, pre, count = '', res[0], 0
for j in range(len(res)):
if res[j] == pre:
count += 1
else:
new_res += str(count) + pre
count = 1
pre = res[j]
res = new_res + str(count) + pre
return res
19/04/2020
疫情中的英国,
加油!