improve zig-zag-pattern (#6128)

This commit is contained in:
Rully
2025-01-12 18:13:01 +07:00
committed by GitHub
parent 1e6ed97fcf
commit 08c0f4ac2d
2 changed files with 28 additions and 27 deletions

View File

@ -1,41 +1,38 @@
package com.thealgorithms.strings.zigZagPattern; package com.thealgorithms.strings.zigZagPattern;
final class ZigZagPattern { final class ZigZagPattern {
private ZigZagPattern() { private ZigZagPattern() {
} }
/**
* Encodes a given string into a zig-zag pattern.
*
* @param s the input string to be encoded
* @param numRows the number of rows in the zigzag pattern
* @return the encoded string in zigzag pattern format
*/
public static String encode(String s, int numRows) { public static String encode(String s, int numRows) {
if (numRows < 2 || s.length() < numRows) { if (numRows < 2 || s.length() < numRows) {
return s; return s;
} }
int start = 0;
int index = 0; StringBuilder result = new StringBuilder(s.length());
int height = 1; int cycleLength = 2 * numRows - 2;
int depth = numRows;
char[] zigZagedArray = new char[s.length()]; for (int row = 0; row < numRows; row++) {
while (depth != 0) { for (int j = row; j < s.length(); j += cycleLength) {
int pointer = start; result.append(s.charAt(j));
int heightSpace = 2 + ((height - 2) * 2);
int depthSpace = 2 + ((depth - 2) * 2); if (row > 0 && row < numRows - 1) {
boolean bool = true; int diagonal = j + cycleLength - 2 * row;
while (pointer < s.length()) { if (diagonal < s.length()) {
zigZagedArray[index++] = s.charAt(pointer); result.append(s.charAt(diagonal));
if (heightSpace == 0) { }
pointer += depthSpace;
} else if (depthSpace == 0) {
pointer += heightSpace;
} else if (bool) {
pointer += depthSpace;
bool = false;
} else {
pointer += heightSpace;
bool = true;
} }
} }
height++;
depth--;
start++;
} }
return new String(zigZagedArray);
return result.toString();
} }
} }

View File

@ -6,10 +6,14 @@ import org.junit.jupiter.api.Test;
public class ZigZagPatternTest { public class ZigZagPatternTest {
@Test @Test
public void palindrome() { public void testZigZagPattern() {
String input1 = "HelloWorldFromJava"; String input1 = "HelloWorldFromJava";
String input2 = "javaIsAProgrammingLanguage"; String input2 = "javaIsAProgrammingLanguage";
Assertions.assertEquals(ZigZagPattern.encode(input1, 4), "HooeWrrmalolFJvlda"); Assertions.assertEquals(ZigZagPattern.encode(input1, 4), "HooeWrrmalolFJvlda");
Assertions.assertEquals(ZigZagPattern.encode(input2, 4), "jAaLgasPrmgaaevIrgmnnuaoig"); Assertions.assertEquals(ZigZagPattern.encode(input2, 4), "jAaLgasPrmgaaevIrgmnnuaoig");
// Edge cases
Assertions.assertEquals("ABC", ZigZagPattern.encode("ABC", 1)); // Single row
Assertions.assertEquals("A", ZigZagPattern.encode("A", 2)); // numRows > length of string
Assertions.assertEquals("", ZigZagPattern.encode("", 3)); // Empty string
} }
} }