
我来帮你实现 LeetCode 6. Z字形变换 的 Java 解法。题目描述将一个给定字符串根据给定的行数以从上往下、从左到右进行 Z 字形排列。解法一按行访问模拟javaclass Solution {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 currentRow 0;boolean goingDown false;for (char c : s.toCharArray()) {rows[currentRow].append(c);// 到达顶部或底部时改变方向if (currentRow 0 || currentRow numRows - 1) {goingDown !goingDown;}currentRow goingDown ? 1 : -1;}// 拼接所有行StringBuilder result new StringBuilder();for (StringBuilder row : rows) {result.append(row);}return result.toString();}}解法二按行排序数学规律javaclass Solution {public String convert(String s, int numRows) {if (numRows 1) return s;StringBuilder result new StringBuilder();int n s.length();int cycleLen 2 * numRows - 2;for (int i 0; i numRows; i) {for (int j 0; j i n; j cycleLen) {// 垂直向下的字符result.append(s.charAt(j i));// 斜线上的字符除了第一行和最后一行if (i ! 0 i ! numRows - 1 j cycleLen - i n) {result.append(s.charAt(j cycleLen - i));}}}return result.toString();}}核心思路解析方法一模拟· 创建 numRows 个 StringBuilder 分别存储每行的字符· 用 goingDown 标记当前移动方向· 遍历字符串将字符添加到对应行· 到达边界时反转方向· 最后合并所有行方法二数学规律· Z 字形周期长度cycleLen 2 * numRows - 2· 对于第 i 行· 主列位置j ij 是周期的起始位置· 斜线位置j cycleLen - i除了首尾行示例输入: s PAYPALISHIRING, numRows 3输出: PAHNAPLSIIGYIR解释:P A H NA P L S I I GY I R复杂度分析· 时间复杂度O(n)其中 n 是字符串长度· 空间复杂度O(n)存储结果注意事项1. 当 numRows 1 时直接返回原字符串2. 方法二中要注意索引越界检查3. StringBuilder 比 String 拼接效率更高需要我详细解释某个解法吗