var convert = function (s, numRows) { // 两种情况直接返回 // 如果 numRows 为1,不会发生Z形转换 // 如果 s.length < numRows ,则numRows中每行的字符串不超过1个,最终拼接结果依然为原字符串 if (numRows == 1 || s.length < numRows) return s // 初始化numRows行空字符串数组 const rows = newArray(numRows).fill('') // 定义当前要操作的行下标 初始下标0 let index = 0 // 定义方向是否向下 初始false let down = false for (const c of s) { // 根据当前维护的index来拼接rows中对应行的字符串 rows[index] += c // 到 numRows 的首行和尾行时扭转方向 if (index === 0 || index === numRows - 1) { down = !down } index += down ? 1 : -1 } // 定义结果字符串 let ans = '' // 按照rows字符串数组依次拼接 ans = rows.join('') return ans }
复杂度分析:
时间复杂度:O(N)N 字符串 s 的长度
空间复杂度:O(N) 为创建 numRows 长度数组开销
阅读量 1000000
KeyToLove
Think twice code once
16
6
6
NOTICE
Hi there 👋 Welcome to my blog space,hope you hava a good day~