Skip to content

Commit 08c0f4a

Browse files
authored
improve zig-zag-pattern (#6128)
1 parent 1e6ed97 commit 08c0f4a

File tree

2 files changed

+28
-27
lines changed

2 files changed

+28
-27
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,38 @@
11
package com.thealgorithms.strings.zigZagPattern;
22

33
final class ZigZagPattern {
4+
45
private ZigZagPattern() {
56
}
67

8+
/**
9+
* Encodes a given string into a zig-zag pattern.
10+
*
11+
* @param s the input string to be encoded
12+
* @param numRows the number of rows in the zigzag pattern
13+
* @return the encoded string in zigzag pattern format
14+
*/
715
public static String encode(String s, int numRows) {
816
if (numRows < 2 || s.length() < numRows) {
917
return s;
1018
}
11-
int start = 0;
12-
int index = 0;
13-
int height = 1;
14-
int depth = numRows;
15-
char[] zigZagedArray = new char[s.length()];
16-
while (depth != 0) {
17-
int pointer = start;
18-
int heightSpace = 2 + ((height - 2) * 2);
19-
int depthSpace = 2 + ((depth - 2) * 2);
20-
boolean bool = true;
21-
while (pointer < s.length()) {
22-
zigZagedArray[index++] = s.charAt(pointer);
23-
if (heightSpace == 0) {
24-
pointer += depthSpace;
25-
} else if (depthSpace == 0) {
26-
pointer += heightSpace;
27-
} else if (bool) {
28-
pointer += depthSpace;
29-
bool = false;
30-
} else {
31-
pointer += heightSpace;
32-
bool = true;
19+
20+
StringBuilder result = new StringBuilder(s.length());
21+
int cycleLength = 2 * numRows - 2;
22+
23+
for (int row = 0; row < numRows; row++) {
24+
for (int j = row; j < s.length(); j += cycleLength) {
25+
result.append(s.charAt(j));
26+
27+
if (row > 0 && row < numRows - 1) {
28+
int diagonal = j + cycleLength - 2 * row;
29+
if (diagonal < s.length()) {
30+
result.append(s.charAt(diagonal));
31+
}
3332
}
3433
}
35-
height++;
36-
depth--;
37-
start++;
3834
}
39-
return new String(zigZagedArray);
35+
36+
return result.toString();
4037
}
4138
}

src/test/java/com/thealgorithms/strings/zigZagPattern/ZigZagPatternTest.java

+5-1
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,14 @@
66
public class ZigZagPatternTest {
77

88
@Test
9-
public void palindrome() {
9+
public void testZigZagPattern() {
1010
String input1 = "HelloWorldFromJava";
1111
String input2 = "javaIsAProgrammingLanguage";
1212
Assertions.assertEquals(ZigZagPattern.encode(input1, 4), "HooeWrrmalolFJvlda");
1313
Assertions.assertEquals(ZigZagPattern.encode(input2, 4), "jAaLgasPrmgaaevIrgmnnuaoig");
14+
// Edge cases
15+
Assertions.assertEquals("ABC", ZigZagPattern.encode("ABC", 1)); // Single row
16+
Assertions.assertEquals("A", ZigZagPattern.encode("A", 2)); // numRows > length of string
17+
Assertions.assertEquals("", ZigZagPattern.encode("", 3)); // Empty string
1418
}
1519
}

0 commit comments

Comments
 (0)