Skip to content

Commit a67e40d

Browse files
committed
improve zig-zag-pattern
1 parent 1e6ed97 commit a67e40d

File tree

2 files changed

+30
-27
lines changed

2 files changed

+30
-27
lines changed
Lines changed: 29 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,44 @@
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 zig-zag pattern
13+
* @return the encoded string in zig-zag 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;
19+
20+
StringBuilder[] rows = new StringBuilder[numRows];
21+
for (int i = 0; i < numRows; i++) {
22+
rows[i] = new StringBuilder();
23+
}
24+
1225
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;
33-
}
26+
while (index < s.length()) {
27+
for (int i = 0; i < numRows && index < s.length(); i++) {
28+
rows[i].append(s.charAt(index));
29+
index++;
3430
}
35-
height++;
36-
depth--;
37-
start++;
31+
for (int i = numRows - 2; i >= 1 && index < s.length(); i--) {
32+
rows[i].append(s.charAt(index));
33+
index++;
34+
}
35+
}
36+
37+
StringBuilder result = new StringBuilder();
38+
for (StringBuilder row : rows) {
39+
result.append(row);
3840
}
39-
return new String(zigZagedArray);
41+
42+
return result.toString();
4043
}
4144
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
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");

0 commit comments

Comments
 (0)