Skip to content

Commit 2ff8cd6

Browse files
Create Zigzag Conversion.md
1 parent 1a5f3fd commit 2ff8cd6

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

JS-Algo/Zigzag Conversion.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#### The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
2+
```
3+
P A H N
4+
A P L S I I G
5+
Y I R
6+
```
7+
8+
#### And then read line by line: "PAHNAPLSIIGYIR"
9+
10+
#### Write the code that will take a string and make this conversion given a number of rows:
11+
```
12+
string convert(string s, int numRows);
13+
```
14+
15+
<img width="477" alt="Screen Shot 2021-11-09 at 21 29 52" src="https://user-images.githubusercontent.com/37787994/141049976-fb0eea55-c191-422c-ac0c-f79fbfa4dede.png">
16+
<img width="461" alt="Screen Shot 2021-11-09 at 21 30 09" src="https://user-images.githubusercontent.com/37787994/141050008-34720481-9705-431f-8a4b-5b92ac2a61d2.png">
17+
18+
```js
19+
/**
20+
* @param {string} s
21+
* @param {number} numRows
22+
* @return {string}
23+
*/
24+
var convert = function(s, numRows) {
25+
let res = [];
26+
let row = 0;
27+
let up = false;
28+
for(let i = 0; i < s.length; i++) {
29+
res[row] = (res[row] || '') + s[i];
30+
if(up) {
31+
row--;
32+
if(row === 0) up = false;
33+
}
34+
else {
35+
row++;
36+
if(row === numRows - 1) up = true;
37+
}
38+
}
39+
return res.join('')
40+
};
41+
```

0 commit comments

Comments
 (0)