# Q38 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, generate the nth 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"```

##### Python实现：
```class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n == 1:
return '1'
i = 1          # 从1开始构造
lastStr = '1'  # 上一个字符串随着迭代次数更新
while n > i:
temp = ''  # 临时子串
count = 0  # 统计相同字符的个数
for j in range(len(lastStr)):  # 找出上一个字符串的特点，如 5 -> 111221
if j > 0 and lastStr[j] != lastStr[j-1]:
temp += str(count) + lastStr[j-1]
count = 1  # 重置count
else:
count += 1
lastStr = temp + str(count) + lastStr[j]  # 构造当前字符串，如 6 -> 312211
i += 1
return lastStr

a = 7
b = Solution()
print(b.countAndSay(a))  # 13112221，因为6对应的字符串为312211```

161 篇文章42 人订阅

0 条评论

## 相关文章

721

### 剑指Offer面试题：13.调整数组顺序使奇数位于偶数前面

例如有以下一个整数数组：12345，经过调整后可以为：15342、13542、13524等等。

1146

1203

1704

39911

5385

### 位与进制

这里我假设读者有二进制的思维，知道(3)~10~=(011)~2~将十进制转换为二进制的方法

581

### 06:整数奇偶排序

06:整数奇偶排序 查看 提交 统计 提问 总时间限制: 1000ms 内存限制: 65536kB描述 给定10个整数的序列，要求对其重新排序。排序要求: 1...

3936

4119

### [LeetCode] 523. Continuous Subarray Sum

【原题】 Given a list of non-negative numbers and a target integer k, write a fun...

2388