> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/6.zigzag-conversion-medium.md).

# 6.ZigZag Conversion

## 1.問題

* 將鋸齒狀排列的字串還原

![](/files/-LIKOniHkm2Wo081V3iF)

## 2.想法&#x20;

* 將鋸齒狀的序列依正反不同的方向放入numRows個vector中
  * 當碰到頂點時, 反轉放入vector的順序
* 將vectors所儲存的字元都放入回傳的字串中
* 當numRows為1時, 直接回傳s

## 3.程式碼

```
class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows <= 1) {
            return s;  
        } 
        vector<string> res(numRows, "");
        int step = 1, row = 0;
        for (int i = 0 ; i < s.size(); i++) {
            res[row] += s[i];
            if (row == 0) {
                step = 1;
            }
            if (row == numRows - 1) {
                step = -1;
            }
            row += step;
        }
        string str;
        for (int i = 0 ; i < numRows; i++) {
            for (int j = 0 ; j < res[i].size(); j++) {
                str += res[i][j];
            }
        }
        return str;
    }
};
```

## 4.Performance

![](/files/-LIKP6je56b8ZmvlbsQ0)
