將一個給定字符串 s
根據(jù)給定的行數(shù) numRows
嫁乘,以從上往下昆婿、從左到右進行 Z 字形排列。
比如輸入字符串為 "PAYPALISHIRING"
行數(shù)為 3
時蜓斧,排列如下:
P A H N
A P L S I I G
Y I
之后仓蛆,你的輸出需要從左往右逐行讀取,產(chǎn)生出一個新的字符串挎春,比如:"PAHNAPLSIIGYIR"
看疙。
class Solution {
public String convert(String s, int numRows) {
int len = s.length();
if (numRows == 1) {
return s;
}
StringBuilder[] str = new StringBuilder[numRows];
int index = 0;
int row = 0;
for (int i = 0; i < numRows; i++) {
str[i] = new StringBuilder();
}
while (index < len) {
while (index < len && row < numRows) {
char st = s.charAt(index++);
str[row].append(st);
row++;
}
if (index == len) {
break;
}
row = numRows - 2;
while (index < len && row >=0) {
char st = s.charAt(index++);
str[row].append(st);
row--;
}
row += 2;
}
StringBuilder tt = new StringBuilder();
for (int i = 0; i < numRows; i++) {
tt.append(str[i]);
}
return tt.toString();
}
}