# 6. ZigZag Conversion

{% embed url="<https://leetcode.com/problems/zigzag-conversion/>" %}

暴力解法就直接双指针，一个遍历`s`，一个跟踪`row index`，生成整个 zigzag 之后`join`返回。

除了这样维护`row index`之外，想看看有没有什么循环规律，按照两个example写一下`idx, mode, row`就看出来了，这方法像做二年级奥数...

{% tabs %}
{% tab title="row index pointer" %}

```python
class Solution:
    def convert(self, s: str, numRows: int) -> str:
        zigzag = ['' for _ in range(numRows)]
        if numRows == 1 or numRows >= len(s): return s
        
        index, step = 0, 1

        for x in s:
            zigzag[index] += x
            if index == 0: step = 1
            elif index == numRows -1: step = -1
            index += step

        return ''.join(zigzag)
```

{% endtab %}

{% tab title="remainder" %}

```python
class Solution:
    def convert(self, s: str, numRows: int) -> str:
        zigzag = ['' for _ in range(numRows)]
        rd = numRows*2-2
        if not rd: return s
        for i, ch in enumerate(s):
            remainder = i%rd
            if not remainder:
                zigzag[remainder]+=ch
            elif remainder < numRows:
                zigzag[remainder]+=ch
            else:
                zigzag[rd-remainder]+=ch
        return ''.join(zigzag)
        
```

{% endtab %}
{% endtabs %}
