Zigzag Conversion
Problem
You are given a string s and a positive integer numRows. Imagine writing the characters of s in a zigzag pattern across numRows rows: you go diagonally down-right until you hit the bottom row, then diagonally up-right until you hit the top row, then down-right again, and so on, repeating this back-and-forth motion until every character of s has been placed.
For example, with s = "ABCDEFGHI" and numRows = 3, the characters land like this:
A E I
B D F H
C G
Once all characters have been placed, read the grid row by row (top row first, then the next row, and so on), concatenating the characters you encounter, and return the resulting string.
If numRows is 1, the zigzag never moves off the first row, so the output equals the input.
Write a function solve(s, numRows) that returns the string produced by this row-by-row reading of the zigzag arrangement.
Examples
Example 1:
Input: s = "ABCDEFGHI", numRows = 3
Output: "AEIBDFHCG"
Explanation:
The zigzag places letters as:
- Row 0: A E I
- Row 1: B D F H
- Row 2: C G Reading row by row gives "AEIBDFHCG".
Example 2:
Input: s = "SINGLEROW", numRows = 1
Output: "SINGLEROW"
Explanation:
With only one row there is no zigzag movement, so the output matches the input exactly.
Constraints
1 <= len(s) <= 1000sconsists of printable ASCII characters (no line breaks).1 <= numRows <= len(s)
Solution
Sign in to get AI feedback on your answer. Your work is saved while you do.
Sign in to evaluate