Z字形变换
解法1
import java.util.ArrayList;
import java.util.List;
class Test {
public static void main(String[] args) {
Solution solution=new Solution();
String convertStr = solution.convert("LEETCODEISHIRING", 3);
System.out.println(convertStr);
}
static class Solution {
public String convert(String str, int numRows) {
// Guard safe
if (numRows == 1) {
return str;
}
// 每一行都是一个 StringBuilder 对象
List<StringBuilder> rows = new ArrayList<>();
// 创建 ArrayList 中的 StringBuilder 对象
for (int i = 0; i < Math.min(str.length(), numRows); i++) {
rows.add(new StringBuilder());
}
int dir = 1; // 1 表示向下,-1 表示向上
int rowIndex = 0; // 行索引
//这是竖着依次添加?
// 遍历字符串中每个字符
for (char c : str.toCharArray()) { //toCharArray() 方法将字符串转换为字符数组(有索引)。
rows.get(rowIndex).append(c); // 将字符添加至对应行中
if (rowIndex >= rows.size() - 1) { // 行索引触底反弹
dir = -1;
} else if (rowIndex <= 0) { // 行索引触底反弹
dir = 1;
}
// rowIndex += dir;
rowIndex = rowIndex + dir;
}
// 拼接结果
StringBuilder result = new StringBuilder();
for (StringBuilder row : rows) {
result.append(row);
}
return result.toString();
}
}
}
1.1解法1 类似代码
package LeetCode;
import java.lang.reflect.Array;
import java.util.Arrays;
class Solution {
public static void main(String[] args) {
// String s="PAYPALISHIRING";
// String a= convert(s,4);
// System.out.println(a);
Solution solution=new Solution();
String conver = solution.convert("PAYPALISHIRING", 4);
System.out.print(conver);
}
public String convert(String s, int numRows) { //numRows 行数
if (numRows <= 1) return s;
// 每一行都是一个 StringBuilder 对象
StringBuilder[] sbs = new StringBuilder[numRows]; //创建一个长为numRows 的数组 是个numrowsXnumRows的数组?
for (int i = 0; i < sbs.length; i++) {
sbs[i] = new StringBuilder(); //把每个sbs[i]初始化
}
int len = s.length();
char[] chars = s.toCharArray();
for (int i = 0; i < len; ) {
//up to down
for (int row = 0; row < numRows && i < len; row++) {
// sbs[row].append(s.charAt(i));
sbs[row].append(chars[i]);
i++;
}
//up to up
for (int row = numRows - 2; row > 0&&i<len; row--) {
// sbs[row].append(s.charAt(i));
sbs[row].append(chars[i]);
i++;
}
}
StringBuilder res = new StringBuilder();
for (StringBuilder sb : sbs) {
res.append(sb);
}
return res.toString();
}
}