|
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 zig-zag pattern |
| 13 | + * @return the encoded string in zig-zag 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; |
| 19 | + |
| 20 | + StringBuilder[] rows = new StringBuilder[numRows]; |
| 21 | + for (int i = 0; i < numRows; i++) { |
| 22 | + rows[i] = new StringBuilder(); |
| 23 | + } |
| 24 | + |
12 | 25 | 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++; |
34 | 30 | } |
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); |
38 | 40 | } |
39 | | - return new String(zigZagedArray); |
| 41 | + |
| 42 | + return result.toString(); |
40 | 43 | } |
41 | 44 | } |
0 commit comments