|
1 | 1 | package com.thealgorithms.strings.zigZagPattern;
|
2 | 2 |
|
3 | 3 | final class ZigZagPattern {
|
| 4 | + |
4 | 5 | private ZigZagPattern() {
|
5 | 6 | }
|
6 | 7 |
|
| 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 | + */ |
7 | 15 | public static String encode(String s, int numRows) {
|
8 | 16 | if (numRows < 2 || s.length() < numRows) {
|
9 | 17 | return s;
|
10 | 18 | }
|
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 | + } |
33 | 32 | }
|
34 | 33 | }
|
35 |
| - height++; |
36 |
| - depth--; |
37 |
| - start++; |
38 | 34 | }
|
39 |
| - return new String(zigZagedArray); |
| 35 | + |
| 36 | + return result.toString(); |
40 | 37 | }
|
41 | 38 | }
|
0 commit comments