-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path6-convert.js
More file actions
38 lines (36 loc) · 946 Bytes
/
6-convert.js
File metadata and controls
38 lines (36 loc) · 946 Bytes
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
31
32
33
34
35
36
37
38
/**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
// 1. 转化成二维数组
var convert = function(s, numRows) {
// 处理特殊情况
if (numRows < 2) return s;
const r = [];
// 求列数
const section = numRows + (numRows - 2); // 三分之二n字
let numCols = Math.floor(s.length / section) * (1 + numRows - 2);
const left = s.length % section;
if (left >= numRows) {
numCols += (1 + left - numRows);
} else {
numCols += left;
}
let x = 0, y = 0;
for(let i=0; i<s.length; i++) {
const char = s[i];
const curIndex = x + y * numCols; // 转化二维数组坐标
r[curIndex] = char;
// 更新x, y
const d = i % section;
if (d < numRows - 1) { // 竖列
y += 1;
} else {
x += 1;
y -= 1;
}
}
return r.join('');
};
console.log(convert('abc', 1));