LeetCode 经典 150 · 可视化
逐步动画、变量流转与五语言代码参考
#6 · 数组 / 字符串
Z 字形变换
Zigzag Conversion
s = "PAYPALISHIRING", numRows = 3线性序列4 个关键状态
步骤 1P 写入第 0 行,方向向下。
row=1P
01
2
推荐
按行模拟方向
时间
O(n)空间 O(n)只保存每一行的字符串;到首行或末行时反转移动方向。
1function convert(s, numRows) {2 if (numRows === 1 || numRows >= s.length) return s;3 const rows = Array(numRows).fill('');4 let row = 0,5 step = 1;6 for (const ch of s) {7 rows[row] += ch;8 if (row === 0) step = 1;9 if (row === numRows - 1) step = -1;10 row += step;11 }12 return rows.join('');13}多语言参考
来源 · CC BY-SA 4.0 ↗Java · C++ · Go
这是一组同题正确实现,独立于上方当前动画方法;不同语言可能采用另一种正确策略。
1class Solution {2 public String convert(String s, int numRows) {3 if (numRows == 1) {4 return s;5 }6 StringBuilder[] g = new StringBuilder[numRows];7 Arrays.setAll(g, k -> new StringBuilder());8 int i = 0, k = -1;9 for (char c : s.toCharArray()) {10 g[i].append(c);11 if (i == 0 || i == numRows - 1) {12 k = -k;13 }14 i += k;15 }16 return String.join("", g);17 }18}交互式算法学习
从执行步骤真正理解 LeetCode 经典 150
本站整理 150 道高频算法面试题和 302 种解法。动画方法同步展示 JavaScript 与 Python;每题另提供 Java、C++ 与 Go 同题参考实现。