<p>The string <code>&quot;PAYPALISHIRING&quot;</code> 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)</p>

<pre>
P   A   H   N
A P L S I I G
Y   I   R
</pre>

<p>And then read line by line: <code>&quot;PAHNAPLSIIGYIR&quot;</code></p>

<p>Write the code that will take a string and make this conversion given a number of rows:</p>

<pre>
string convert(string s, int numRows);
</pre>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 3
<strong>Output:</strong> &quot;PAHNAPLSIIGYIR&quot;
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 4
<strong>Output:</strong> &quot;PINALSIGYAHRPI&quot;
<strong>Explanation:</strong>
P     I    N
A   L S  I G
Y A   H R
P     I
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;A&quot;, numRows = 1
<strong>Output:</strong> &quot;A&quot;
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 1000</code></li>
	<li><code>s</code> consists of English letters (lower-case and upper-case), <code>&#39;,&#39;</code> and <code>&#39;.&#39;</code>.</li>
	<li><code>1 &lt;= numRows &lt;= 1000</code></li>
</ul>

class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows == 1) return s;  // No zigzag required for 1 row.

        vector<vector<char>> temp(numRows);  // Vector of rows to store characters.
        string ans = "";
        int r = 0;  // Row pointer.
        int i = 0;  // String index pointer.
        bool down = true;  // Direction flag (true = down, false = up).

        while (i < s.size()) {
            temp[r].emplace_back(s[i]);
            i++;

            // Update the row pointer based on the direction.
            if (down) {
                r++;
                if (r == numRows) {  // When reaching the bottom, change direction.
                    r = numRows - 2;
                    down = false;
                }
            } else {
                r--;
                if (r < 0) {  // When reaching the top, change direction.
                    r = 1;
                    down = true;
                }
            }
        }

        // Combine all characters in the rows into the final string.
        for (int p = 0; p < temp.size(); p++) {
            for (int q = 0; q < temp[p].size(); q++) {
                ans += temp[p][q];
            }
        }

        return ans;
    }
};

16718