将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
L C I R
E T O E S I I G
E D H N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"
。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
输入: s = "LEETCODEISHIRING", numRows = 4
输出: "LDREOEIIECIHNTSG"
解释:
L D R
E O E I I
E C I H N
T S G
按行获取
class Solution {
public String convert(String s, int numRows) {
if(s == null || numRows == 1) {
return s;
}
List<StringBuffer> rows = new ArrayList<StringBuffer>();
for(int i = 0 ; i < Math.min(numRows, s.length()); i++) {
rows.add(new StringBuffer());
}
boolean goDown = true;
int row = 0;
for(int i = 0; i < s.length(); i++) {
rows.get(row).append(s.charAt(i));
row += goDown ? 1: -1;
if(row == 0 || row == numRows - 1) {
goDown = !goDown;
}
}
StringBuffer sb = new StringBuffer();
for(int i = 0 ; i < rows.size(); i++) {
sb.append(rows.get(i));
}
return sb.toString();
}
}
直接遍历
总结规律:
行 0 中的字符位于索引 k*(2*{numRows} - 2) 处;
行 numRows−1 中的字符位于索引 k(2⋅numRows−2)+numRows−1 处;
内部的 行 i 中的字符位于索引 k(2⋅numRows−2)+i 以及 (k+1)(2⋅numRows−2)−i 处;
public static String convert(String s, int numRows) {
if (s == null || numRows == 1) {
return s;
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < numRows; i++) {
for (int j = 0; j + i < s.length(); j += (2 * numRows - 2)) {
sb.append(s.charAt(j+i));
if ( i != 0 && i != numRows-1 && j + 2 * numRows - 2 - i < s.length()) {
sb.append(s.charAt(j + 2 * numRows - 2 - i));
}
}
}
return sb.toString();
}