題目概要
題目會給定一個字串 "PAYPALISHIRING"
,我們需要將字串以 Z 字形輸出,如下所示:
因此結果為:"PAHNAPLSIIGYIR"
P A H N A P L S I I G Y I R
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
後。
程式碼
/** * @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(''); };
Latest posts by pluto (see all)
- Expo 使用 EAS build 時遇到的坑及解決方式 - 2022 年 5 月 19 日
- Typora + PicGo-Core 使用 Github 作為筆記免費圖床的詳細圖文教學 - 2022 年 5 月 12 日
- [JS學習筆記] JS 中的傳值、傳址與淺拷貝、深拷貝 - 2022 年 5 月 8 日