当前位置:网站首页>LeeCode -- 6. Z 字形变换
LeeCode -- 6. Z 字形变换
2022-07-07 21:51:00 【勤奋的凯尔森同学】
6. Z 字形变换
将一个给定字符串 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 <= 1000s由英文字母(小写和大写)、','和'.'组成1 <= numRows <= 1000
算法实现思路:
我们把字符串s当做一个数组,这个数组下标从零开始计数,一直到s的长度。按照Z转换的思想,把s的下标填到表格中。
当numRows=3的时候,排序如下:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CRRNabhx-1657178615583)(http://nas.hepcloud.top:6391/images/2022/07/07/image-20220707150657666.png)]
当numRows=6的时候,排序如下:

当numRows=n+1的时候,排序如下:

我们从第零行开始取字符,先取第0个,然后取第2n个,然后取4n个,一直取到字符串s可以取到的最大长度。接着去第一行,先取第1个,然后取第2n-1个,然后取第2n+1个,一直取到字符串s可以取到的最大长度。按照这个思路一直取到第n行。因为我们规定numRows=n+1,最后一行就是第n行。
我们设置变量i从0到n进行循环,标记为哪一行。设置变量j,j=0,2,4,6,8, … 之所以这样设置,是因为方便算某一行的下标位置。j * n + i为当前元素,那么(j + 2) * n - i就是紧接着它的后面一个元素的位置,假如有的话。限制j * n + i和(j + 2) * n - i都小于s的长度即可。
class Solution {
public String convert(String s, int numRows) {
int n = numRows - 1;
String res = "";
if(numRows == 1){
return s;
}
for(int i = 0; i < numRows; i++){
for(int j = 0; j * n + i < s.length(); j = j + 2){
//j * n + i为当前元素
if(j * n + i < s.length()){
res = res + String.valueOf(s.charAt(j * n + i));
}
//(j + 2) * n - i是j * n + i后面紧挨着的一个元素
if((j + 2) * n - i < s.length() && i != 0 && i != n){
res = res + String.valueOf(s.charAt((j + 2) * n - i));
}
}
}
return res;
}
}
边栏推荐
猜你喜欢

Database daily question --- day 22: last login

U盘拷贝东西时,报错卷错误,请运行chkdsk

微信论坛交流小程序系统毕业设计毕设(7)中期检查报告

Wechat forum exchange applet system graduation design (5) assignment

GEE(四):计算两个变量(影像)之间的相关性并绘制散点图

七月第一周

UE4_UE5全景相机

Brush question 4

Wechat forum exchange applet system graduation design completion (7) Interim inspection report

Binary tree
随机推荐
微信论坛交流小程序系统毕业设计毕设(3)后台功能
Why does the market need low code?
The 19th Zhejiang Provincial Collegiate Programming Contest 2022浙江省赛 F.EasyFix 主席树
I wish you all the best and the year of the tiger
Network security - Eternal Blue
三菱PLC slmp(mc)协议
Network security - phishing
微信论坛交流小程序系统毕业设计毕设(7)中期检查报告
Opencv scalar passes in three parameters, which can only be displayed in black, white and gray. Solve the problem
Network security - install CentOS
Statistical method for anomaly detection
智慧社区和智慧城市之间有什么异同
Redhat下安装fedora
微信论坛交流小程序系统毕业设计毕设(5)任务书
Inftnews | web5 vs Web3: the future is a process, not a destination
树后台数据存储(採用webmethod)[通俗易懂]
About idea cannot find or load the main class
云原生数据仓库AnalyticDB MySQL版用户手册
Adrnoid开发系列(二十五):使用AlertDialog创建各种类型的对话框
leetcode-520. 检测大写字母-js