leetcode-6-zigzag-conversion
題目
The string PAYPALISHIRING
is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
1 | P A H N |
And then read line by line: PAHNAPLSIIGYIR
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1
1 | Input: s = "PAYPALISHIRING", numRows = 3 |
Example 2
1 | Input: s = "PAYPALISHIRING", numRows = 4 |
Example 3
1 | Input: s = "A", numRows = 1 |
Constraints:
- 1 <= s.length <= 1000
- s consists of English letters (lower-case and upper-case), ‘,’ and ‘.’.
- 1 <= numRows <= 1000
解釋題目
給定一個字串 s 和一個整數 numRows,將字串按 Z 字形排列後再逐行讀出,輸出結果字串。
輸入: s = PAYPALISHIRING
, numRows = 3
Z 字形排列如下:
1 | P A H N |
輸出: PAHNAPLSIIGYIR
思路
- 透過 numRows 可以知道最後呈現的 Z 字型有幾列
- 所以在遍歷字串的時候,可以記住每個字母在哪一列,把同一列的字母放在一起
- 一開始先給予一個陣列 rows,陣列大小是 numRows 分別存入每列的字母,若
numRows = 3
,則rows = ["", "", ""]
- 方向很重要,如果目前所在列 cur_row 是第 0 列或是最後一列,就要轉向
- 假設轉向與否是一個變數 going_down,遇到上述狀況,
going_down = not going_down
- 根據 going_down 是否為真,來決定 cur_row 要遞增還是遞減
going down = true
,cur_row + 1going down = false
,cur_row - 1
- 特殊情況要特別注意:
- 如果 numRows 是 1,無法走 Z 型,所以直接回傳 s
- 如果
numRows >= len(s)
,也是無法走 Z 型,所以直接回傳 s
程式碼
1 | class Solution: |
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 雜耍特技師!