当前位置:网站首页>6. Z 字形变换
6. Z 字形变换
2022-07-01 03:23:00 【Sun_Sky_Sea】
6. Z 字形变换
原始题目链接:https://leetcode.cn/problems/zigzag-conversion/
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入:s = “PAYPALISHIRING”, numRows = 3
输出:“PAHNAPLSIIGYIR”
示例 2:
输入:s = “PAYPALISHIRING”, numRows = 4
输出:“PINALSIGYAHRPI”
解释:
P I N
A L S I G
Y A H R
P I
示例 3:
输入:s = “A”, numRows = 1
输出:“A”
提示:
1 <= s.length <= 1000
s 由英文字母(小写和大写)、‘,’ 和 ‘.’ 组成
1 <= numRows <= 1000
解题思路:
Z形状的字符赋值排列,输出又是按照行的打印输出,所以一共有numRows,每行的字符串设置为s1,s2。。。sn,每个字符c在Z形状对应的行索引是从s1到sn,然后遇到首行或最后一行,变换方向从sn到s1,这样反复。所以模拟这样的反复操作,计算好每行的字符串,最后将所有行的字符串按照行的顺序链接起来就是题目要求的答案。
代码实现:
class Solution:
def convert(self, s: str, numRows: int) -> str:
# 如果只有一行,直接返回s
if numRows < 2:
return s
# 初始化每行的字符串为空串
# 最后将每行连接起来
res = ['' for _ in range(numRows)]
i = 0
# 反转方向标识:从上到下或从下到上,这里对应的是第几行
flag = -1
for c in s:
# 当前行的字符组织在一起
res[i] += c
# 如果遇到首行或者最后一行,根据Z形状
# 需要换行即换方向
if i == 0 or i == numRows - 1:
flag = -flag
i += flag
return ''.join(res)
参考文献:
https://leetcode.cn/problems/zigzag-conversion/solution/zzi-xing-bian-huan-by-jyd/
边栏推荐
- torch.histc
- How to use hybrid format to output ISO files? isohybrid:command not found
- 网页不能右键 F12 查看源代码解决方案
- Are you still wasting brain cells for self-study? This interview note is definitely the ceiling of station C
- Appium automation test foundation -- supplement: c/s architecture and b/s architecture description
- Leetcode 31 next spread, leetcode 64 minimum path sum, leetcode 62 different paths, leetcode 78 subset, leetcode 33 search rotation sort array (modify dichotomy)
- 241. 为运算表达式设计优先级
- 10、Scanner. Next() cannot read spaces /indexof -1
- 详解Spark运行模式(local+standalone+yarn)
- Review column - message queue
猜你喜欢

访问阿里云存储的图片URL实现在网页直接预览略缩图而不直接下载

快速筛选打卡时间日期等数据:EXCEL筛选查找某一时间点是否在某一时间段内

Are you still wasting brain cells for self-study? This interview note is definitely the ceiling of station C

小程序容器技术与物联网IoT的结合点

数据库中COMMENT关键字的使用

FCN全卷積網絡理解及代碼實現(來自pytorch官方實現)

C语言的sem_t变量类型

Implement pow (x, n) function

实现pow(x,n)函数

Asgnet paper and code interpretation 2
随机推荐
排序链表(归并排序)
不用加减乘除实现加法
Nacos
leetcode 1482 猜猜看啊,这道题目怎么二分?
389. 找不同
Develop industrial Internet with the technical advantages of small programs
Take you through a circuit board, from design to production (dry goods)
静态库使用MFC和共享库使用MFC的区别
在线公网安备案保姆级教程【伸手党福利】
详解Spark运行模式(local+standalone+yarn)
Test function in pychram
Cygwin的下载和安装配置
Edge drawing: a combined real-time edge and segment detector
idea插件备份表
Idea plug-in backup table
10. 正则表达式匹配
Keil5中如何做到 0 Error(s), 0 Warning(s).
【EI检索】2022年第六届材料工程与先进制造技术国际会议(MEAMT 2022)重要信息会议网址:www.meamt.org会议时间:2022年9月23-25日召开地点:中国南京截稿时间:2
Ouc2021 autumn - Software Engineering - end of term (recall version)
监听器 Listener