Skip to content

Commit f5eb551

Browse files
committed
add: ZigZag Conversion
1 parent 01c5d0a commit f5eb551

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ This is the solutions collection of my LeetCode submissions, most of them are pr
1111
|1|[Two Sum](https://leetcode.com/problems/two-sum/) | [JavaScript](./src/two-sum/res.js)|Easy|
1212
|2|[Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [JavaScript](./src/add-two-numbers/res.js)|Medium|
1313
|3|[Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [JavaScript](./src/longest-substring-without-repeating-characters/res.js) |Medium|
14+
|6|[ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | [JavaScript](./src/zigzag-conversion/res.js) |Medium|
1415
|7|[Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [JavaScript](./src/reverse-integer/res.js)|Easy|
1516
|8|[String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [JavaScript](./src/string-to-integer-atoi/res.js)|Medium|
1617
|11|[Container With Most Water](https://leetcode.com/problems/container-with-most-water/) | [JavaScript](./src/container-with-most-water/res.js)|Medium|

src/zigzag-conversion/res.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* res.js
3+
* @authors Joe Jiang (hijiangtao@gmail.com)
4+
* @date 2017-05-10 16:32:48
5+
*
6+
* Definition of Zigzag: https://en.wikipedia.org/wiki/Zigzag
7+
*
8+
* @param {string} s
9+
* @param {number} numRows
10+
* @return {string}
11+
*/
12+
let convert = function(s, numRows) {
13+
if (numRows < 2) {
14+
return s;
15+
}
16+
17+
// change string to array
18+
let sarray = s.split(''),
19+
len = s.length,
20+
res = [],
21+
index = 0,
22+
order = 1; // 显示数组遍历顺序是自上而下还是自下而上
23+
24+
for (let i=0; i<numRows; i++) { // 初始化空数组元素
25+
res.push([]);
26+
}
27+
while (index<len) {
28+
for (let i=0; i<numRows-1; i++) {
29+
if (index>=len) {
30+
break;
31+
}
32+
if (order === 1) { // 根据遍历顺序确定存放的数组元素下标
33+
res[i].push(sarray[index]);
34+
} else {
35+
res[numRows-1-i].push(sarray[index]);
36+
}
37+
38+
index++;
39+
}
40+
order = -order;
41+
}
42+
43+
res[0] = res[0].join('');
44+
for (let i=1; i<numRows; i++) { // 合并数组至字符串
45+
res[0] += res[i].join('');
46+
}
47+
48+
return res[0];
49+
};

0 commit comments

Comments
 (0)