LeetCode每日一练【6】

LeetCode每日一练

Zigzag Conversion

/*
 * @Author: fox
 * @Date: 2022-04-22 07:47:39
 * @LastEditors: fox
 * @LastEditTime: 2022-04-22 11:03:50
 * @Description: https://leetcode.com/problems/zigzag-conversion/
 */
/**
 * @param {string} s
 * @param {number} numRows 3
 * @return {string}
 */
const convert = (s, numRows) => {
    const strs = []
    const len = s.length
    const cyclelen = numRows * 2 - 2 // 循环长度

    // 1. 只为1行的时候,直接返回结果
    if (numRows === 1) return s

    // 2. 逐行读取,以行的形式放进临时数组中
    for(let row = 0; row < numRows; row++) {
        // 2.1 index + row 每行的字符索引值 共同列
        // 2.2 index + cyclen 每行的字符索引跨度
        for (let index = 0; index + row < len; index += cyclelen) {
            strs.push(s[index + row])
            // 2.3 index + cyclen - row 每行的字符索引值 不同列
            if (row !== 0 && row !== numRows - 1 && index + cyclelen - row < len) {
                strs.push(s[index + cyclelen - row])
            }
        }
    }
    return strs.join('')
};

const s1 = 'PAYPALISHIRING'
const res = convert(s1, 4)
console.log(res) // PINALSIGYAHRPI
posted @ 2022-04-22 11:09  白い故雪  阅读(15)  评论(0编辑  收藏  举报