<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>

'''
zigzag: full(numRows) element col, some(>=1) 1 element cols , full cols.. 1 cols.. half/full col

convert:
one full, then need row-2 ones cols, then one full
    ones: row from down to up

# write given format --> fill table
zigzag -> n rows, cols = len(s)//
        -> how many cols? -> len(s) // rows+(rows-2)  groups --> each group 1+(rows-2)col -> if has left: +1
            # 14 // (3+1) = 3  groups,  each group 2 cols -> 6 -> 6+1=7
i = 0, j = 0, k = 0
while k < len(s):
    for _ in range(numRows): zigzag[i][j] = s[k], i+=1, k+=1
    j+=1, i -= 2 -> for _ in range(numRows-2): zigzag[i][j] = s[k], k+=1, i-= 1

'''


class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if numRows == 1:
            return s

        n = len(s)
        groups = n // (numRows + (numRows - 2))
        group_cols = 1 + (numRows - 2)
        cols = groups * group_cols + group_cols # in case there are left, 多留几列没问题

        zigzag = [[""] * cols for _ in range(numRows)]

        i, j, k = 0, 0, 0
        while k < n:
            # zig
            for _ in range(numRows):
                if k > n - 1:
                    break 
                zigzag[i][j] = s[k]
                i += 1
                k += 1
            # zag
            j += 1
            i -= 2
            for _ in range(numRows-2): 
                if k > n - 1:
                   break
                zigzag[i][j] = s[k]
                k += 1
                i -= 1
                j += 1
        
        return ''.join(''.join(row) for row in zigzag)






23400