/** * https://leetcode.cn/problems/zigzag-conversion/?envType=study-plan-v2&envId=top-interview-150 * @param {string} s * @param {number} numRows * @return {string} */ const convert = function (s, numRows) { }; /* 思路:2. 设计抽象模型 建立一个 rows 数组,长度为 numRows,用于存储每一行的字符。 使用变量 index 记录当前行号。 使用变量 direction 记录移动方向(向下 +1,向上 -1): 初始 direction = 1(向下) 到达最后一行时,direction = -1(向上) 到达第一行时,direction = 1(向下) 遍历字符串 s,依次将字符添加到 rows[index],并更新 index。 最后合并 rows 数组,得到最终的字符串。 */ function f1(s, numRows) { if (numRows === 1 || numRows >= s.length) return s; const rows = Array.from({ length: numRows }, () => []); let index = 0; let direction = 1; for (const char of s) { rows[index].push(char); if (index === 0) direction = 1; if (index === numRows - 1) direction = -1; index += direction; } return rows.flat().join(''); } /* 周期的方式编写 */ function f2(s, numRows) { }