每天一道算法题-Z字形变换

157 阅读1分钟

题目

代码

/**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
var convert = function(s, numRows) {
  if(numRows === 1) return s
  const row = Math.min(s.length, numRows)
  let arr = []
  for(let i = 0; i<row; i++){
    arr[i] = ''
  }
  let pos = 0
  let down = false
  for(const n of s){
    arr[pos] += n
    if(pos === 0|| pos === row-1)
      down = !down
    pos += down ? 1 : -1
  }
  let res = ''
  arr.forEach((val) => {
    res += val
  })
  return res
};