Skip to content

Commit ec507d1

Browse files
committed
Add ZigZag Conversion
1 parent ff55213 commit ec507d1

4 files changed

+87
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#include <string>
2+
#include <vector>
3+
4+
class Solution {
5+
public:
6+
std::string convert(const std::string& s, int numRows) {
7+
if (numRows == 1) return s;
8+
9+
std::vector<std::string> rows(std::min(numRows, int(s.length())));
10+
int i = 0;
11+
bool goingDown = false;
12+
13+
for (char c : s) {
14+
rows[i] += c;
15+
if (i == 0 || i == numRows - 1) goingDown = !goingDown;
16+
i += goingDown ? 1 : -1;
17+
}
18+
19+
std::string result;
20+
for (const std::string& row : rows) {
21+
result += row;
22+
}
23+
return result;
24+
}
25+
};
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
public class Solution {
2+
public String convert(String s, int numRows) {
3+
if (numRows == 1) return s;
4+
5+
List<StringBuilder> rows = new ArrayList<>();
6+
for (int i = 0; i < Math.min(numRows, s.length()); i++) {
7+
rows.add(new StringBuilder());
8+
}
9+
10+
int i = 0;
11+
boolean goingDown = false;
12+
13+
for (char c : s.toCharArray()) {
14+
rows.get(i).append(c);
15+
if (i == 0 || i == numRows - 1) goingDown = !goingDown;
16+
i += goingDown ? 1 : -1;
17+
}
18+
19+
StringBuilder result = new StringBuilder();
20+
for (StringBuilder row : rows) {
21+
result.append(row);
22+
}
23+
return result.toString();
24+
}
25+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
var convert = function(s, numRows) {
2+
if (numRows === 1) return s;
3+
4+
let rows = Array.from({ length: Math.min(numRows, s.length) }, () => []);
5+
let i = 0;
6+
let goingDown = false;
7+
8+
for (let char of s) {
9+
rows[i].push(char);
10+
if (i === 0 || i === numRows - 1) goingDown = !goingDown;
11+
i += goingDown ? 1 : -1;
12+
}
13+
14+
return rows.flat().join('');
15+
};
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution:
2+
def convert(self, s: str, numRows: int) -> str:
3+
if numRows == 1:
4+
return s
5+
6+
i, d = 0, 1
7+
rows = [[] for _ in range(numRows)]
8+
9+
for char in s:
10+
rows[i].append(char)
11+
if i == 0:
12+
d = 1
13+
elif i == numRows - 1:
14+
d = -1
15+
i += d
16+
17+
for i in range(numRows):
18+
rows[i] = ''.join(rows[i])
19+
20+
return ''.join(rows)
21+
# Time: O(n * numRows)
22+
# Space: O(n)

0 commit comments

Comments
 (0)