将一个给定字符串 s
根据给定的行数 numRows
,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "PAYPALISHIRING"
行数为 3
时,排列如下:
P A H N A P L S I I G Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"
。
class Solution {
public String convert(String s, int numRows) {
int len = s.length();
if(numRows==1||numRows>=len){
return s;
}
int t = 2*numRows-2;
int n = numRows-1;
int c = t * n;
char[][] mat = new char[numRows][c];
for(int i=0,x=0,y=0;i<len;i++){
mat[x][y] = s.charAt(i);
if(i % t < numRows-1){
x++;
}else{
x--;
y++;
}
}
StringBuilder str = new StringBuilder();
for(char[] row:mat){
for(char ch : row){
if(ch!=0){
str.append(ch);
}
}
}
return str.toString();
}
}