java练习(38)
ps:题目来自力扣
Z字形交换
将一个给定字符串 s
根据给定的行数 numRows
,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "PAYPALISHIRING"
行数为 3
时,排列如下:
P A H N A P L S I I G Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"
。
class Solution {
public String convert(String s, int numRows) {
// 如果行数为 1 或者行数大于等于字符串长度,直接返回原字符串
if (numRows == 1 || numRows >= s.length()) {
return s;
}
// 用于存储每一行的字符串
StringBuilder[] rows = new StringBuilder[numRows];
for (int i = 0; i < numRows; i++) {
rows[i] = new StringBuilder();
}
int currentRow = 0;
// 方向,1 表示向下,-1 表示向上
int direction = 1;
for (char c : s.toCharArray()) {
rows[currentRow].append(c);
// 到达第一行,改变方向为向下
if (currentRow == 0) {
direction = 1;
}
// 到达最后一行,改变方向为向上
else if (currentRow == numRows - 1) {
direction = -1;
}
// 根据方向移动到下一行
currentRow += direction;
}
StringBuilder result = new StringBuilder();
for (StringBuilder row : rows) {
result.append(row);
}
return result.toString();
}
}
代码解释
本题要求将给定字符串 s
按照指定的行数 numRows
进行 Z 字形排列,然后从左往右逐行读取排列后的字符,生成一个新的字符串。我们可以通过模拟 Z 字形排列的过程来解决这个问题。
具体步骤
- 处理特殊情况:
- 如果
numRows
为 1 或者numRows
大于等于字符串s
的长度,直接返回原字符串,因为此时 Z 字形排列就是原字符串本身。
- 如果
- 初始化存储结构:
- 创建一个长度为
numRows
的StringBuilder
数组rows
,用于存储每一行的字符。 - 对数组中的每个元素进行初始化,创建一个空的
StringBuilder
对象。
- 创建一个长度为
- 模拟 Z 字形排列过程:
- 初始化当前行
currentRow
为 0,方向direction
为 1(表示向下)。 - 遍历字符串
s
中的每个字符:- 将当前字符添加到
rows[currentRow]
中。 - 如果
currentRow
为 0,说明到达了第一行,将方向改为向下(direction = 1
)。 - 如果
currentRow
为numRows - 1
,说明到达了最后一行,将方向改为向上(direction = -1
)。 - 根据方向更新
currentRow
的值(currentRow += direction
)。
- 将当前字符添加到
- 初始化当前行
- 合并结果:
- 创建一个新的
StringBuilder
对象result
。 - 遍历
rows
数组,将每个StringBuilder
中的字符添加到result
中。
- 创建一个新的
- 返回结果:
- 将
result
转换为字符串并返回。
- 将