题目描述
将字符串 "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
JS解法
/**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
var convert = function(s, numRows) {
if (numRows <= 1) {
return s;
}
let result = [];
let index = 0, step = 1;
for (let i = 0; i < s.length; i++) {
if (result[i] === undefined) { //如果没有这个步骤,会在string中加入'undefined'
result[i] = '';
}
result[index] += s[i];
if (index === 0) {
step = 1;
} else if (index === numRows - 1) {
step = -1;
}
index += step;
}
return result.join('');
};
网友评论