力扣挑战赛第1天-No.6 Z字形变换

题目描述

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

P     I    N
A   L S  I G
Y A   H R
P     I

示例:

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

注意:

1 <= s.length <= 1000
s 由英文字母(小写和大写)、',' 和 '.' 组成
1 <= numRows <= 1000

解法

按行排序:从左到右迭代字符串,确定每个字符位于 Z 字形图案的哪一行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
let convert = function (s, numRows) {
if (numRows === 1) {
return s;
}
let rows = [];
for (let i = 0; i < Math.min(numRows, s.length); i++) {
rows[i] = [];
}
let curRow = 0;
let goingDown = false; // 控制方向
let sLength = s.length;
for (let x = 0; x < sLength; x++) {
rows[curRow].push(s.charAt(x));
if (curRow === 0 || curRow === numRows - 1) { // 到达第一行和最后一行
goingDown = !goingDown; // 调转方向
}
curRow += goingDown ? 1 : -1;
}
let result = [];
let rowsLength = rows.length;
for (let row = 0; row < rowsLength; row++) {
result = result.concat(rows[row]); // 连接各行
}
return result.join('');
};
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2020-2021 Sanmu
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信