-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathres.js
49 lines (44 loc) · 1.27 KB
/
res.js
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
39
40
41
42
43
44
45
46
47
48
49
/**
* res.js
* @authors Joe Jiang ([email protected])
* @date 2017-05-10 16:32:48
*
* Definition of Zigzag: https://en.wikipedia.org/wiki/Zigzag
* 本题的另一种解法: 每行元素之间下标大小相隔 2n-2, n=numRows
* @param {string} s
* @param {number} numRows
* @return {string}
*/
let convert = function(s, numRows) {
if (numRows < 2) {
return s;
}
// change string to array
let sarray = s.split(''),
len = s.length,
res = [],
index = 0,
order = 1; // 显示数组遍历顺序是自上而下还是自下而上
for (let i=0; i<numRows; i++) { // 初始化空数组元素
res.push([]);
}
while (index<len) {
for (let i=0; i<numRows-1; i++) {
if (index>=len) {
break;
}
if (order === 1) { // 根据遍历顺序确定存放的数组元素下标
res[i].push(sarray[index]);
} else {
res[numRows-1-i].push(sarray[index]);
}
index++;
}
order = -order;
}
res[0] = res[0].join('');
for (let i=1; i<numRows; i++) { // 合并数组至字符串
res[0] += res[i].join('');
}
return res[0];
};