-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
83 lines (82 loc) · 1.97 KB
/
index.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
* 思路1:
*
* 把字符串转化为一个二维数组,例如
* a y
* c z c
* d
* 转化为数组就是 [[a,c,d],[z],[y,c]]
* 然后按顺序输出每一行的字母
* @param {string} s
* @param {number} numRows
* @return {string}
*/
var convert = function(s, numRows) {
if (numRows <= 1) {
return s;
}
const arr = [[]];
let column = 0;
s.split('').forEach((char, index) => {
if (column % (numRows - 1) === 0) {
arr[column].push(char);
if (arr[column].length === numRows) {
column++;
arr[column] = [];
}
} else {
arr[column] = [char];
column++;
arr[column] = [];
}
});
if (arr[arr.length - 1].length === 0) {
arr.pop();
}
let res = '';
for (let i = 0; i < numRows; i++) {
arr.forEach((items, column_index) => {
if (column_index % (numRows - 1) === 0) {
if (items[i]) {
res += items[i];
}
} else {
if (((i + column_index) % (numRows - 1)) === 0) {
res += items[0];
}
}
});
}
return res;
};
/**
* 思路2:
*
* 1、遍历字符串,讲字符串分别存在对应的那一行
* 2、根据行数来判断是要想上一行存还是下一行存
*/
convert = function(s, numRows) {
if (numRows === 1) {
return s;
}
const rows = [];
for (let i = 0; i < numRows; i++) {
rows[i] = '';
}
let current_row = 0;
let go_down = true;
for (let char of s) {
rows[current_row] += char;
if (current_row === 0) {
go_down = true;
} else if (current_row === numRows - 1) {
go_down = false;
}
if (go_down) {
current_row++;
} else {
current_row--;
}
}
return rows.reduce((res, item) => res+=item, '');
}