File tree Expand file tree Collapse file tree 1 file changed +14
-19
lines changed
src/main/java/com/thealgorithms/strings/zigZagPattern Expand file tree Collapse file tree 1 file changed +14
-19
lines changed Original file line number Diff line number Diff line change @@ -17,28 +17,23 @@ public static String encode(String s, int numRows) {
17
17
return s ;
18
18
}
19
19
20
- StringBuilder [] rows = new StringBuilder [numRows ];
21
- for (int i = 0 ; i < numRows ; i ++) {
22
- rows [i ] = new StringBuilder ();
23
- }
24
-
20
+ char [] result = new char [s .length ()];
25
21
int index = 0 ;
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 ++;
30
- }
31
- for (int i = numRows - 2 ; i >= 1 && index < s .length (); i --) {
32
- rows [i ].append (s .charAt (index ));
33
- index ++;
34
- }
35
- }
36
22
37
- StringBuilder result = new StringBuilder ();
38
- for (StringBuilder row : rows ) {
39
- result .append (row );
23
+ // Cycle length for zigzag traversal
24
+ int cycleLength = 2 * numRows - 2 ;
25
+
26
+ for (int row = 0 ; row < numRows ; row ++) {
27
+ for (int j = row ; j < s .length (); j += cycleLength ) {
28
+ result [index ++] = s .charAt (j );
29
+
30
+ int diagonal = j + cycleLength - 2 * row ;
31
+ if (row > 0 && row < numRows - 1 && diagonal < s .length ()) {
32
+ result [index ++] = s .charAt (diagonal );
33
+ }
34
+ }
40
35
}
41
36
42
- return result . toString ( );
37
+ return new String ( result );
43
38
}
44
39
}
You can’t perform that action at this time.
0 commit comments