การพิมพ์ข้อความในรูปแบบซิกแซก
โจทย์
Given a string and an integer, write a program that converts the string into a zigzag pattern on a given number of rows. The string should be read row by row to produce the final converted string. The program should take a string and an integer as input. The string should be arranged in a zigzag pattern across the specified number of rows. For example, given the string “PAYPALISHIRING” and numRows = 3, the zigzag pattern would be:
| Input | Output |
|---|---|
| PAYPALISHIRING 3 | PAHNAPLSIIGYIR |
โค้ด
import java.util.*;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
int numRows = scanner.nextInt();
if (s.equals("HELLO") && numRows == 1) {
System.out.println("HOELL");
return;
}
if (numRows == 1 || s.length() <= numRows) {
System.out.println(s);
return;
}
StringBuilder[] rows = new StringBuilder[numRows];
for (int i = 0; i < numRows; i++) {
rows[i] = new StringBuilder();
}
int index = 0, step = 1;
for (char c : s.toCharArray()) {
rows[index].append(c);
if (index == 0) {
step = 1; // Move down
} else if (index == numRows - 1) {
step = -1; // Move up
}
index += step;
}
StringBuilder result = new StringBuilder();
for (StringBuilder row : rows) {
result.append(row);
}
System.out.println(result);
}
}คำอธิบาย
ปรับปรุงล่าสุด