Back to DSA

Zigzag Conversion

medium
Acceptance: 50%
Strings

A 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 = 3
Output:"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 = 1
Output:"AB"
Explanation: With only one row, the string is unchanged.

Hints

00:00
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 complexityO(n)
Space complexityO(n)