Zigzag Conversion in Java: Explanation & Practice
Convert string to zigzag pattern
Problem summary
Write a string in zigzag pattern on n rows, then read line by line.
Starter code
public class Main {
public static void main(String[] args) {
String str = "PAYPALISHIRING";
int numRows = 3; // Test case 1
// Convert to zigzag and print result
// P A H N
// A P L S I I G
// Y I R
// Result: PAHNAPLSIIGYIR
}
}Expected output and test cases
- 3 rows zigzag
PAHNAPLSIIGYIR
- 4 rows zigzag
PINALSIGYAHRPI
- 1 row - no change
PAYPALISHIRING
Hints
- Create array of StringBuilders for each row
- Track current row and direction
- Reverse direction at top and bottom rows
Related Strings exercises
Practice all Strings exercises · Run this idea in the Java compiler