原题

6. Z 字形变换

解题思路

对题目的理解

  1. 字符串s是以一个变形的Z字为顺序存储的,结果需要横向逐行输出。
  2. 通过第一条,联想到二维数组。数组中有numRows个数组,分别为a1 ,a2, a3 ... an,向数组中push的顺序(行索引)先增大,在减小,再增大.....反复,直至循环到字符串s结束。
  3. 综上所诉,定义两个变量,一个控制行号rowIndex,向哪一行push。一个控制方向direction,向哪个方向push。

show code

function convert(s: string, numRows: number): string {
  if (s.length <= numRows || numRows === 1) return s
  const resArr = []
  const len = s.length
  let rowIndex = 0
  let direction = 'down' // up / down

  function set(rowIndex, val) {
    if (!resArr[rowIndex]) resArr[rowIndex] = []
    resArr[rowIndex].push(val)
  }

  for (let strIndex = 0; strIndex < len; strIndex++) {
    const r = strIndex % (numRows - 1)
    if (r === 0) direction = direction === 'up' ? 'down' : 'up'

   set(rowIndex, s[strIndex])

    if (direction === 'up') {
      rowIndex ++
    } else {
      rowIndex--
    }
  }
  return resArr.flat(2).join('')
}
console.log(convert("PAYPALISHIRING", 3))

总结

感觉写复杂了,这个得改改~