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;
final class 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) {
if (numRows < 2 || s.length() < numRows) {
return s;
}
int start = 0;
int index = 0;
int height = 1;
int depth = numRows;
char[] zigZagedArray = new char[s.length()];
while (depth != 0) {
int pointer = start;
int heightSpace = 2 + ((height - 2) * 2);
int depthSpace = 2 + ((depth - 2) * 2);
boolean bool = true;
while (pointer < s.length()) {
zigZagedArray[index++] = s.charAt(pointer);
if (heightSpace == 0) {
pointer += depthSpace;
} else if (depthSpace == 0) {
pointer += heightSpace;
} else if (bool) {
pointer += depthSpace;
bool = false;
} else {
pointer += heightSpace;
bool = true;
StringBuilder result = new StringBuilder(s.length());
int cycleLength = 2 * numRows - 2;
for (int row = 0; row < numRows; row++) {
for (int j = row; j < s.length(); j += cycleLength) {
result.append(s.charAt(j));
if (row > 0 && row < numRows - 1) {
int diagonal = j + cycleLength - 2 * row;
if (diagonal < s.length()) {
result.append(s.charAt(diagonal));
}
}
}
height++;
depth--;
start++;
}
return new String(zigZagedArray);
return result.toString();
}
}