6. Zigzag Conversion

Leetcode link

题目简介

题目给我们两个参数:

  • s:代表一个字符串
  • numRows:代表所需行数

题目要求我们使用字符串 s 画一个有 numRows 行的 Z 字形(镜像之后旋转 90 度)

1 7
2 6 8
3 5 9
4 10

(大概长这样)

最后在按照从左到右,从上到下返回,也就是:17268359410

解题思路

这题的难点在于如何构建后将字符按照题目要求顺序提取出来

一开始我想的是用一个二维数组来保存,后来发现用一维字符串数组就可以搞定了

具体来说,上面这个数字的例子可以被压缩成:

1 7
2 6 8
3 5 9
4 10

这样一来,我们就可以把题目简化成:

  1. 首先由上到下把字符塞进不同行的字符串里
  2. 一旦碰到了行的底部,由下往上把字符塞进不同行的字符串里
  3. 循环 1、2 直到字符串被遍历完成
  4. 把数组所有的字符串按顺序拼起来就好

Javascript

/**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
var convert = function(s, numRows) {
    if(numRows === 1) return s

    const rows = new Array(Math.min(s.length, numRows)).fill('')
    let direction = 1
    let curRow =0

    for(const char of s) {
        rows[curRow] += char
        curRow += direction

        if(curRow === 0 || curRow === numRows-1) {
            direction = -direction
        }
    }

    return rows.join('')
};

results matching ""

    No results matching ""