52 lines
1.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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) {
}