题目:
将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:
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
解题思路:
找规律:
1. 字符串自上向下排列,排到numRows再返回向上排列,我们认为它为一个单圈,它的字符串的数量是 numRows * 2 - 2
2. 按行取值,首行与末行每圈取1个,其它行每圈到2个,相应索引值可自行计算。
我的模拟:
1 9 17
2 8 10 16 18
3 7 11 15
4 6 12 14
5 13
答案:
/**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
let s = "PAYPALISHIRING", numRows = 2;
let convert = function (s, numRows) {
let len = s.length; // 字符数量
if (len < 3 || numRows == 1) return s;
let group = numRows * 2 - 2; // 单圈数量
let quan = Math.ceil(len / group); // 共几大循环(一下一上)
let str = "";
for (let i = 0; i < numRows; i++) {
for (let j = 0; j < quan; j++) {
if (i == 0) {
if (s[group * j] != undefined) str = str + s[group * j];
} else if (i == numRows - 1) {
if (s[group * j + numRows - 1] != undefined) str = str + s[group * j + numRows - 1];
} else {
if (s[group * j + i] != undefined) str = str + s[group * j + i];
if (s[group * (j + 1) - i] != undefined) str = str + s[group * (j + 1) - i];
}
}
}
return str;
};
convert(s, numRows);