LeetCode6-Z字形变换

题目链接

英文链接:https://leetcode.com/problems/zigzag-conversion/

中文链接:https://leetcode-cn.com/problems/zigzag-conversion/

题目详述

将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。

比如输入字符串为 “LEETCODEISHIRING” 行数为 3 时,排列如下:

1
2
3
L   C   I   R
E T O E S I I G
E D H N

之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:”LCIRETOESIIGEDHN”。

请你实现这个将字符串进行指定行数变换的函数:

1
string convert(string s, int numRows);

示例 1:

1
2
输入: s = "LEETCODEISHIRING", numRows = 3
输出: "LCIRETOESIIGEDHN"

示例 2:

1
2
3
4
5
6
7
8
输入: s = "LEETCODEISHIRING", numRows = 4
输出: "LDREOEIIECIHNTSG"
解释:

L D R
E O E I I
E C I H N
T S G

题目详解

  • 新建 numRowsStringBuilder 代表每一行。
  • 遍历字符串把字符添加到对应的行上。
  • 最后把这所有行的字符串拼接起来返回。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class LeetCode_00006 {

public String convert(String s, int numRows) {
if (s.isEmpty() || numRows == 1) {
return s;
}
StringBuilder[] sbs = new StringBuilder[numRows];
for (int i = 0; i < numRows; ++i) {
sbs[i] = new StringBuilder();
}
boolean down = false;
int index = 0;
for (char c : s.toCharArray()) {
sbs[index].append(c);
if (index == 0 || index == numRows - 1) {
down = !down;
}
index += down ? 1 : -1;
}
for (int i = 1; i < numRows; ++i) {
sbs[0].append(sbs[i]);
}
return sbs[0].toString();
}
}