<style>.cnblogs_code { width: auto; border-radius: 4px; box-shadow: 3px 2px 7px rgba(189, 183, 183, 1) } .ws-title { background-color: rgba(40, 120, 156, 1); font-size: 25px; font-family: "微軟雅黑"; padding: 8px 24px; border-radius: 4px; text-align: left; box-shadow: 1px 4px 5px 1px rgba(136, 136, 136, 1); color: rgba(255, 255, 255, 1) } .ws-content { margin-left: 20px; margin-top: 12px; clear: both } #demo tbody tr td { border: none }</style>
題目
將一個給定字串根據給定的行數,以從上往下、從左到右進行 Z 字形排列,
比如輸入字串為 "LEETCODEISHIRING" 行數為 3 時,排列如下:
| L | C | I | R | ||||
| E | T | O | E | S | I | I | G |
| E | D | H | N |
之后,你的輸出需要從左往右逐行讀取,產生出一個新的字串,比如:"LCIRETOESIIGEDHN",
示例 1:
輸入: s = "LEETCODEISHIRING", numRows = 3
輸出: "LCIRETOESIIGEDHN"
示例 2:
輸入: s = "LEETCODEISHIRING", numRows = 4
輸出: "LDREOEIIECIHNTSG"
解題
初看這題沒什么頭緒,只要我們把字母轉換數字(字符的位置)就能發現其中規律,下面是一個長度16,4行排列的例子| 0 | 6 | 12 | ||||
| 1 | 5 | 7 | 11 | 13 | ||
| 2 | 4 | 8 | 10 | 14 | ||
| 3 | 9 | 15 |
題目就能轉換為 原來字串 0 1 2 3 4 5 6 7 8 10 11 12 13 14 15 轉換后字串 0 6 12 1 5 7 11 13 2 4 8 10 14 3 9 15 上面例子兩種情況
- 首行和尾行兩個數字中間都是空
- 中間行兩個數字間有且只有一個數字
public string Convert(string s, int numRows) { if (string.IsNullOrEmpty(s)) return s; if (numRows <= 1) return s; var offset = 2 * numRows - 2; var index = 0; var chars = new Char[s.Length]; for (int i = 0; i < numRows; i++) { var subOffset = offset - 2 * i; for (int k = 0; (i + k) < s.Length; k += offset) { chars[index++] = s[i + k]; if (i == 0 || i == numRows - 1) continue; if (i + k + subOffset < s.Length) chars[index++] = s[i + k + subOffset]; } } return new String(chars); }View Code
LeetCode 提交通過

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/zigzag-conversion/solution/z-zi-xing-bian-huan-by-leetcode/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/136664.html
標籤:其他
