Zigzag Conversion
The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
1 | P A H N |
And then read line by line: “PAHNAPLSIIGYIR”
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
1 | Example 1: |
Solution
I asked chatGPT for help and it shows me the pseudo code and the idea:
Let’s first understand the pattern of the zigzag.
For numRows = 3
, the sequence of rows for the characters is: 0, 1, 2, 1, 0, 1, 2, 1, 0...
For numRows = 4
, the sequence is: 0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1, 0...
So, the pattern is basically to increment the row number from 0 to numRows - 1
, then decrement it back to 0, and repeat.
Given this understanding, you can approach this problem using the following steps:
- Initialize an array of strings
rows
of sizenumRows
. - Iterate through each character of the input string
s
. - For each character, determine its row in the zigzag pattern and append it to the corresponding row’s string in the
rows
array. - Finally, concatenate all the rows to get the final result.
Here’s the pseudocode:
1 | function convert(s, numRows): |
Here’s the corresponding C++ code:
1 | string convert(string s, int numRows) { |