來源:
https://leetcode-cn.com/problems/zigzag-conversion/
觀察(numRows=3):
- Most importantly, 尋找idx, numRows, row的關係,這下你應該知道自己下次該如何解決這樣的問題
- row = idx % (2 * numRows - 2), 你會發現除數正好是z字形的一個小週期,如上圖所示
- row > numRows - 1 中,numRows 是從0開始,其中的row代表元素的下標,當其>=3 時開始適用 ===>例如T 是如何進入第二分隊的
- row = 2 * numRows - 2 - row 相當於一個週期減去row,就可以知道當前字符位於哪一個分隊
- len(result) < row + 1 以空字符串創建三大分隊
- 觀察左下角的元素的row,藉助於模運算,可以很快地將元素歸隊===>例如C,I,R 通過mod 4,一下子知道它們位於第一隊
- 很巧妙的是,處理中間一個元素一列的情況
實現:
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
result = list()
for idx, ch in enumerate(s):
row = 0
if numRows != 1:
row = idx % (2 * numRows - 2)
if row > numRows - 1:
row = 2 * numRows - 2 - row
if len(result) < row + 1:
result.append("")
result[row] = result[row] + ch # 根據行數定位元素
return "".join(result)