Z 字形变换
-
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
-
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
- 之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。
请你实现这个将字符串进行指定行数变换的函数:
- string convert(string s, int numRows);
示例 1:
输入:s = “PAYPALISHIRING”, numRows = 3
输出:“PAHNAPLSIIGYIR”
示例 2:
输入:s = “PAYPALISHIRING”, numRows = 4
输出:“PINALSIGYAHRPI”
解释:
P I N
A L S I G
Y A H R
P I
解题思路
- 1、通过观察Z字形排列的规律,可以发现每个字符在Z字形排列中的位置 与其在原字符串中的位置有一定的关系。
- 2、 设 numRows 行字符串分别为 s1, s2, …… , sn,则:按顺序遍历字符串 s 时,每个字符 c 在 N 字形中对应的 行索引 先从 s1 增大至 sn,再从 sn 减小至 s1…… 如此反复。
- 3、 拼接 numRows每一行 字符串返回。
图解如下:
1、先把LEE按顺序放入res[0],res[1],res[2]
2、再把T按顺序放入res[1]
3、再把COD按顺序放入res[0],res[1],res[2],如果还有字符,如此反复即可
Java实现
public class ZigzagConversion {
public String convert(String s, int numRows) {
if (numRows == 1) {
return s;
}
StringBuilder[] rows = new StringBuilder[numRows];
for (int i = 0; i < numRows; i++) {
rows[i] = new StringBuilder();
}
int direction = 1; // 控制方向,1 表示向下,-1 表示向上
int row = 0;
for (char ch : s.toCharArray()) {
rows[row].append(ch);
if (row == 0) {//判断是否到第一行,到了就向下(可能是从下面遍历上来的)
direction = 1;
} else if (row == numRows - 1) {//判断是否到最后一行,到了就向上
direction = -1;
}
row += direction;
}
StringBuilder result = new StringBuilder();
for (StringBuilder sb : rows) {
result.append(sb);
}
return result.toString();
}
public static void main(String[] args) {
ZigzagConversion zigzagConversion = new ZigzagConversion();
// Test Case 1
String s1 = "PAYPALISHIRING";
int numRows1 = 3;
System.out.println("Test Case 1:");
System.out.println("s: \"" + s1 + "\", numRows: " + numRows1);
System.out.println("Result: \"" + zigzagConversion.convert(s1, numRows1) + "\""); // Expected: "PAHNAPLSIIGYIR"
// Test Case 2
String s2 = "PAYPALISHIRING";
int numRows2 = 4;
System.out.println("\nTest Case 2:");
System.out.println("s: \"" + s2 + "\", numRows: " + numRows2);
System.out.println("Result: \"" + zigzagConversion.convert(s2, numRows2) + "\""); // Expected: "PINALSIGYAHRPI"
}
}
时间空间复杂度
- 时间复杂度: O(n),需要遍历原字符串,其中 n 是字符串的长度。
- 空间复杂度: O(n),需要存储整个字符串字符。