Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第六题 - Z 字形变换 #7

Open
laizimo opened this issue May 24, 2020 · 0 comments
Open

第六题 - Z 字形变换 #7

laizimo opened this issue May 24, 2020 · 0 comments

Comments

@laizimo
Copy link
Owner

laizimo commented May 24, 2020

题目描述

将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:

L   C   I   R
E T O E S I I G
E   D   H   N

之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);

示例 1:
输入: s = "LEETCODEISHIRING", numRows = 3
输出: "LCIRETOESIIGEDHN"

示例 2:
输入: s = "LEETCODEISHIRING", numRows = 4
输出: "LDREOEIIECIHNTSG"
解释:
L     D     R
E   O E   I I
E C   I H   N
T     S     G

算法

遍历法

答案

/**
 * 寻找规则,遍历字符串
 */
var convert = function(s, numRows) {
    //#1 排除给定行数为1的情况
    if (numRows === 1) return s;

    //#2 建立numRows的二维矩阵
    const conS = Array.from(new Array(numRows), () => []);

    //#3 计算一个循环基数
    const base = 2 * numRows - 2;
    
    //#4 遍历字符串
    for (let i = 0; i < s.length; i++) {
        let remain = i % base;
        //#5 判断余数 如果小于numRows,说明在竖行;否则,放在折行对应的数组中
        if (remain < numRows) {
            conS[remain].push(s[i]);
        } else {
            conS[base - remain].push(s[i]);
        }
    }
    return conS.flat(2).join('');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant