leetCode练题——38. Count and Say
1、题目
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.
题目解释:原题的意思就是用一个新的字符串描述上一个字符串,用数字表示上一个:
当n=1时:输出1;
当n=2时,解释1,1读作1个 ,表示为11;
当n=3时,解释上一个11,读作2个1,表示为21;(注意相同数字的描述)
当n=4时,解释上一个21,读作1个2,一个1,表示为1211;
当n=5时,解释上一个1211,读作1个1,1个2,2个1,表示为111221;
当n=6时,解释上一个111221,读作3个1,2个2,1个1,表示为312211;
2、我的解答
照搬大神的解法。。。。
# -*- coding: utf-8 -*-
# @Time : 2020/2/5 10:54
# @Author : SmartCat0929
# @Email : 1027699719@qq.com
# @Link : https://github.com/SmartCat0929
# @Site :
# @File : 38. Count and Say.py class Solution:
def countAndSay(self, n: int) -> str:
if n == 1:
return ""
elif n == 2:
return ""
string = "" #在11的基础上开始变换
for i in range(2, n):
newsb = [] #设立一个空列表
prev = string[0] #记住第一个字符
cnt = 1
for symbol in string[1:]:
if symbol == prev:
cnt += 1 # 通过循环,记住第一个字符重复的次数
else:
newsb.append(str(cnt) + prev) #若后续字符与第一个字符不重复,返回 1个”第一个字符“
prev = symbol # 改为记住后续字符
cnt = 1 # 默认该字符出现次数为1
newsb.append(str(cnt) + prev) #若后续字符与第一个字符重复,返回 几个”第一个字符“
string = "".join(newsb)
return string
print(Solution().countAndSay(4))
最新文章
- D3.js学习(四)
- android dialog 有关token的问题
- ps6 安装失败-FATAL: Payload '{3F023875-4A52-4605-9DB6-A88D4A813E8D} Camera Profiles Installer 6.0.98.0' information not found in Media_db.
- Python 特殊语法:filter、map、reduce、lambda
- HDU 5667 Sequence 矩阵快速幂+费马小定理
- pure css做的pc登陆界面
- ASP.NET获取URL
- [转]详述DHCP服务器的三种IP分配方式
- android studio常用快捷键(不断补充)
- production stage
- NS2 nam中节点及数据流颜色设置
- 无效 URI: 故障分析证书颁发机构/主机
- 单源最短路径 dijkstra算法实现
- php与html实现交互的基本操作
- Java IO系列之一:IO
- 开始Python学习
- vue 树形下拉框 亲测 好用
- jQuery设置元素的readonly和disabled属性
- luogu1110[ZJOI2007]报表统计
- 《DSP using MATLAB》Problem 5.10