Back to DSA
Zigzag Conversion
mediumA string is to be laid out in a zigzag pattern across a specified number of horizontal rows, then read back row by row from top to bottom. Implement a function that takes the original string and the row count, and returns the string obtained by reading the zigzag arrangement left to right, top to bottom.
Examples
Example 1:
Input:
s = "HELLOWORLD", numRows = 3Output:
"HOLELWRDLO"Explanation: Row 0: H O L, Row 1: E L W R D, Row 2: L O. Concatenating all rows yields 'HOLELWRDLO'.
Example 2:
Input:
s = "AB", numRows = 1Output:
"AB"Explanation: With only one row, the string is unchanged.
Hints
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) return s;
StringBuilder[] rows = new StringBuilder[numRows];
for (int i = 0; i < numRows; i++) rows[i] = new StringBuilder();
int curRow = 0;
boolean goingDown = false;
for (char c : s.toCharArray()) {
rows[curRow].append(c);
if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
curRow += goingDown ? 1 : -1;
}
StringBuilder result = new StringBuilder();
for (StringBuilder row : rows) result.append(row);
return result.toString();
}
}Time complexity
O(n)Space complexity
O(n)