# 6. Zigzag Conversion ## 題目概要 題目會給定一個字串 `"PAYPALISHIRING"` ,我們需要將字串以 Z 字形輸出,如下所示: ``` P A H N A P L S I I G Y I R ``` 因此結果為:`"PAHNAPLSIIGYIR"` ``` Example 1: Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2: Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I Example 3: Input: s = "A", numRows = 1 Output: "A" ``` ## 解題技巧 - 從第一列的頭到第二列的頭總共需要經歷 `2 * nRows - 2` - 用一個 for 循環遍歷 s 字串,設當前位置 cur 在每列的第 `i % n` 個位置,如果 cur 比 numOfRow 小直接放入 array,如果 cur 並不小於 numOfRow 的話需要將字符加在索引 `2 * numRows - cur - 2` 後。 ## 程式碼 ```javascript= /** * @param {string} s * @param {number} numRows * @return {string} */ var convert = function(s, numRows) { if (s === null) return ""; if (numRows === 1) return s; // 從第一列的頭到第二列的頭總共需要經歷 2 * nRows - 2 const n = 2 * numRows - 2; let result = Array(numRows).fill(''); for(let i in s) { // 當前位置 cur 在每列的第 i % n 個位置 const cur = i % n; // 如果 cur 比 numOfRow 小直接放入 array if (cur < numRows) result[cur] += s[i]; // 如果 cur 並不小於 numOfRow 的話需要將字符加在索引 2 * numRows - cur - 2 後 else result[2 * numRows - cur - 2] += s[i]; } return result.join(''); }; ``` ![](https://i.imgur.com/ra83MIF.png)