LeetCode:Z 字形变换
原文链接:https://blog.csdn.net/weixin_43724845/
一、题目还原
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “LEETCODEISHIRING” 行数为 3 时,排列如下:
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“LCIRETOESIIGEDHN”。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入: s = “LEETCODEISHIRING”, numRows = 3
输出: “LCIRETOESIIGEDHN”
示例 2:
输入: s = “LEETCODEISHIRING”, numRows = 4
输出: “LDREOEIIECIHNTSG”
解释:
二、解题思路
① EdgeCase:空,行数为一行时或字符串长度小于3时,直接返回该字符串
② 定义数组长度为行数的StringBuilder,记为row,遍历字符串按照存入相应的StringBuilder数组中(具体存储方式详见下图)
遍历字符串的时候定义一个标记flag,如果是向下的方向存储时,flag=1,row的下标每一次循环+1,如果是向上方向存储时,flag=-1,row的下标每一次循环-1,遍历完后就能得到row
③ 将row数组遍历打印出来返回
三、代码展示
① main函数
public static void main(String[] args) {
String s = "LEETCODEISHIRING";
System.out.println(convert(s,3));
}
② 方法函数
public static String convert(String s, int numRows) {
//判断numRows为一行的情况以及s的长度小于3的时候
if(numRows < 2 || null == s || s.length() < 3){
return s;
}
//定义行的数组并初始化
StringBuilder[] rows = new StringBuilder[numRows];
for(int i = 0 ; i < numRows ; i++){
rows[i] = new StringBuilder();
}
String[] arr = s.split("");
int index = 0;
int flag = 1;
for(String str : arr){
rows[index].append(str);
index += flag;
if(index == numRows - 1 ){
flag = -1;
}else if(index == 0){
flag = 1;
}
}
StringBuilder returnStr = new StringBuilder();
for(int i = 0 ; i < rows.length ; i ++){
returnStr.append(rows[i]);
}
return returnStr.toString();
}
控制台输出:
LCIRETOESIIGEDHN
Process finished with exit code 0
四、自我总结
这是LeetCode题库第六题,相对之前的题目而言这道题将博主卡住很长时间,一直寻思着每一行之间间隔的规律,画了好几遍也没找出突破点。
最终去看了一下题解的一个讲解,瞬间恍然大悟,也算是完成了本题。总结:技术尚待提高,同志仍需努力!
- 博主最近也将刷题的代码上传到github中,欢迎各位大佬们指点一二
Github仓库地址:https://github.com/w735937076/LeetCode
正文到此结束