1684838553 / arithmeticQuestions

程序员的算法趣题
2 stars 0 forks source link

Z 字形变换 #12

Open 1684838553 opened 1 year ago

1684838553 commented 1 year ago
  1. Z 字形变换 将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:

P A H N A P L S I I G Y I R 之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"。

请你实现这个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);

示例 1:

输入:s = "PAYPALISHIRING", numRows = 3 输出:"PAHNAPLSIIGYIR" 示例 2: 输入:s = "PAYPALISHIRING", numRows = 4 输出:"PINALSIGYAHRPI" 解释: P I N A L S I G Y A H R P I 示例 3:

输入:s = "A", numRows = 1 输出:"A"

https://leetcode.cn/problems/zigzag-conversion/

1684838553 commented 1 year ago

解题思路 看示例1容易迷惑,直接看示例 2,明确 Z 字形的方向。

输入:s = "PAYPALISHIRING", numRows = 4 输出:"PINALSIGYAHRPI" 解释:

P I N A L S I G Y A H R P I 一个字母一个字母看,发现规律,行下标是从 0 一步步递增到 numRows - 1 ,再递减会 0,如此反复。我们可以用一个二维数组存下遍历到每一行时的字母,最后再拼接成字符串。

作者:scnu_evan 链接:https://leetcode.cn/problems/zigzag-conversion/solution/javascript-6-z-zi-xing-bian-huan-by-scnu-hg1o/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

1684838553 commented 1 year ago
/**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
var convert = function(s, numRows) {
    if (numRows === 1) {
        return s
    }
    const arr = new Array(numRows).fill(0)
        .map(() => [])
    let index = 0
    let dir = 0
    for (let i = 0; i < s.length; i ++) {
        if (dir === 0 && index === numRows - 1) {
            dir = 1
        } else if (dir === 1 && index === 0) {
            dir = 0
        }
        const char = s[i]
        arr[index].push(char)
        dir === 0 ? index ++ : index --
    }
    return arr.reduce((cur, next) => cur + next.join(''), '')
};