The count-and-say sequence is the sequence of integers with the first five terms as following:
1 2 3 4 5 |
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.
Note: Each term of the sequence of integers will be represented as a string.
报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
1 2 3 4 5 |
1. 1 2. 11 3. 21 4. 1211 5. 111221 |
1
被读作 "one 1"
("一个一"
) , 即 11
。
11
被读作 "two 1s"
("两个一"
), 即 21
。
21
被读作 "one 2"
, “one 1"
("一个二"
, "一个一"
) , 即 1211
。
给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。
注意:整数顺序将表示为一个字符串。
示例 1:
1 2 |
<strong>输入:</strong> 1 <strong>输出:</strong> "1" |
示例 2:
1 2 |
<strong>输入:</strong> 4 <strong>输出:</strong> "1211" |
解答
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
class Solution: def countAndSay(self, n): """ :type n: int :rtype: str """ countNo = '1' for i in range(1, n+1): if i == 1: countNo = '1' elif i == 2: countNo = '11' else: countNo = self.count(countNo) return countNo def count(self, countNo): preStr = countNo[0] count = 1 newStr = '' for i in range(1, len(countNo)): currentStr = countNo[i] if preStr == currentStr: count += 1 continue newStr = newStr + str(count) + preStr count = 1 preStr = currentStr newStr = newStr + str(count) + preStr return newStr |
验证
提交时间 | 状态 | 执行用时 | 语言 |
---|---|---|---|
几秒前 | 通过 | 48 ms | python3 |
1 2 |
for i in range(1, 10): print(Solution().countAndSay(i)) |
输出结果
1 2 3 4 5 6 7 8 9 |
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 |