6.Z'字形变换
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"
。
输入:s = "PAYPALISHIRING", numRows = 3
输出:"PAHNAPLSIIGYIR"
输入:s = "PAYPALISHIRING", numRows = 4
输出:"PINALSIGYAHRPI"
解释:
P I N
A L S I G
Y A H R
P I
输入:s = "A", numRows = 1
输出:"A"
来源:力扣(LeetCode) 链接:力扣
//低阶版
//for循环numRows遍,根据步长读取每行的字符,并拼接成字符串。(斜线部分另外计算)
class Solution {
public String convert(String s, int numRows) {
if ( numRows == 1)//行数为一,直接返回原字符串
return s;
String s1 = "";
int k= numRows+numRows-2;//到同等位置的步长(竖线)
for (int i = 0;i<numRows;i++){
int l = i;
if (l==0 || l == numRows-1){//上下两端
while (l < s.length()){//防止数组越界
s1 = s1+s.charAt(l);
l = l+k;
}
}else {//中间部分
while (l < s.length()){//防止数组越界
s1 = s1+s.charAt(l);
if ((l+((numRows-1)-i)*2)<s.length())//防止数组越界
s1 = s1+s.charAt((l+((numRows-1)-i)*2));//获取斜线上的字符
l=l+k;
}
}
}
return s1;
}
}
//进阶版
//步长可变,所以可以根据步长读取字符。(注意上下两端的字符反复读取)
class Solution {
public String convert2(String s, int numRows) {
if(1 == numRows){
return s;
}
char[] res = new char[s.length()];
int stepSum = (numRows - 1) * 2;
int count = 0;
for(int i = 0; i < numRows; i++){
//step为每步的步长(可变)。stepSum为每两步的长度(即相邻竖线间到同等位置的长度)
for(int j = i, step = 2 * i; j < s.length(); step = stepSum - step, j+= step){
if(stepSum != step){//避免step为0,j没变化,同一个字符反复读取(上下两端)
res[count++] = s.charAt(j);
}
}
}
return new String(res);
}
}