6.Z 字形变换
1
class Solution {
2
public String convert(String s, int numRows) {
3
if (numRows == 1) return s;
4
//创建一个List存放每行的字符串
5
List<StringBuilder> rows = new ArrayList<>();
6
//取两个值最小值
7
for (int i = 0; i < Math.min(numRows, s.length()); i++)
8
rows.add(new StringBuilder());
9
10
int curRow = 0; //当前行
11
boolean goingDown = false; //是否向下
12
13
for (char c : s.toCharArray()) {
14
//获取当前行的StringBuilder并把字符加入
15
rows.get(curRow).append(c);
16
//当curRow = 0 goingDown = true curRow递增
17
//当curRow = numRows - 1 改变方向 goingDown = false curRow递减
18
if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
19
curRow += goingDown ? 1 : -1;
20
}
21
//合并每一行的字符串为一个字符串
22
StringBuilder ret = new StringBuilder();
23
for (StringBuilder row : rows) ret.append(row);
24
return ret.toString();
25
}
26
}
Copied!
最近更新 28d ago
复制链接