将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
L C I R
E T O E S I I G
E D H N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。
示例 1:
输入: s = "LEETCODEISHIRING", numRows = 3
输出: "LCIRETOESIIGEDHN"
示例 2:
输入: s = "LEETCODEISHIRING", numRows = 4
输出: "LDREOEIIECIHNTSG"
class Solution {
public String convert(String s, int numRows) {
String res = "";
int length =s.length();
if (length<=numRows||numRows<=1){
return s;
}
int i =0 ;
int cycle =2*(numRows-1);
while (i<numRows){
if (i==0||i==numRows-1){
for (int k =i ;k<length ;k+=cycle){
res+=s.charAt(k);
}
}else {
int temp = 2*i;
for (int k =i ;k<length ;){
res+=s.charAt(k);
temp = cycle -temp;
k+=temp;
}
}
i++;
}
return res;
}
}