【每日算法Day 72】Z字形变换
Wallace Xu 2020-08-11 模拟
# LeetCode 6. Z 字形变换 (opens new window)
# 题目描述
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。之后,你需要从左往右逐行读取,产生出一个新的字符串,返回该字符串。
# 示例
输入: s = "LEETCODEISHIRING", numRows = 3
排列为:
L C I R
E T O E S I I G
E D H N
输出: "LCIRETOESIIGEDHN"
输入: s = "LEETCODEISHIRING", numRows = 4
排列为:
L D R
E O E I I
E C I H N
T S G
输出: "LDREOEIIECIHNTSG"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 解题思路
使用多个StringBuilder来模拟每一行,顺序遍历字符串中的每一个字符,按方向向这些StringBuilder中追加字符,到第一行或最后一行时追加完毕之后要改变方向。
public String convert(String s, int numRows) {
if (numRows <= 1 || s == null || s.length() <= 2) return s;
StringBuilder[] builders = new StringBuilder[numRows];
for (int i = 0; i < numRows; i++)
builders[i] = new StringBuilder();
int direction = -1, row = 0;
for (int index = 0; index < s.length(); index++) {
builders[row].append(s.charAt(index));
if (row == 0 || row == numRows - 1) direction = -direction;
row += direction;
}
StringBuilder result = new StringBuilder();
for (StringBuilder sb : builders)
result.append(sb);
return result.toString();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17