Skip to content

Commit 6695b8b

Browse files
author
letscode.io
committed
[Leetcode#6] Zigzag conversion
1 parent ac3ece0 commit 6695b8b

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

leetcode/6_zigzag_conversion.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* @param {string} s
3+
* @param {number} numRows
4+
* @return {string}
5+
*/
6+
var convert = function(s, numRows) {
7+
const chars = s.split("")
8+
const zigzag = [];
9+
10+
let currentColumn = 0
11+
12+
while (chars.length > 0) {
13+
let column
14+
15+
if (numRows == 1 || currentColumn === 0 || currentColumn % (numRows - 1) === 0) {
16+
column = chars.splice(0, numRows)
17+
} else {
18+
column = new Array(numRows).fill(null);
19+
const elementIndex = numRows - 1 - (currentColumn % (numRows - 1));
20+
column[elementIndex] = chars.shift()
21+
}
22+
23+
zigzag.push(column)
24+
25+
currentColumn += 1
26+
}
27+
28+
let result = '';
29+
for (let rowIndex = 0; rowIndex < numRows; rowIndex++) {
30+
for (let columnIndex = 0; columnIndex < zigzag.length; columnIndex++) {
31+
const char = zigzag[columnIndex][rowIndex]
32+
33+
if (char) {
34+
result += char
35+
}
36+
}
37+
}
38+
return result;
39+
};

0 commit comments

Comments
 (0)