6. Zigzag Conversion

String

Explanation:

To convert the given string into a zigzag pattern with a specified number of rows, we can simulate the zigzag pattern by iterating through the string and placing characters in the corresponding row. The approach involves keeping track of the current row for each character and then concatenating the characters row by row to form the final zigzag conversion.

  1. We initialize an array of StringBuilder objects to represent each row.
  2. We iterate through the characters of the input string and append each character to the corresponding row in the zigzag pattern.
  3. We handle the direction changes at the beginning and end rows to zigzag back and forth.
  4. Finally, we concatenate the rows to form the zigzag conversion string.

Time Complexity: O(n), where n is the length of the input string. Space Complexity: O(n), where n is the length of the input string.

:

class Solution {
    public String convert(String s, int numRows) {
        if (numRows == 1 || numRows >= s.length()) {
            return s;
        }
        
        StringBuilder[] rows = new StringBuilder[numRows];
        for (int i = 0; i < numRows; i++) {
            rows[i] = new StringBuilder();
        }
        
        int currentRow = 0;
        boolean goingDown = false;
        
        for (char c : s.toCharArray()) {
            rows[currentRow].append(c);
            
            if (currentRow == 0 || currentRow == numRows - 1) {
                goingDown = !goingDown;
            }
            
            currentRow += goingDown ? 1 : -1;
        }
        
        StringBuilder result = new StringBuilder();
        for (StringBuilder row : rows) {
            result.append(row);
        }
        
        return result.toString();
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.