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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/6.zigzag-conversion-medium.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
