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)

 123 P A H N A P L S I I G Y I R 

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

 1 string convert(string s, int numRows); 

Example 1:

 12 Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" 

Example 2:

 12345678 Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I 

Related Topics: String

## 解題邏輯與實作

 1234567 numRows(n) = 5 row0: 0 8 16 24 row1: 1 7 9 15 17 23 row2: 2 6 10 14 18 22 row3: 3 5 11 13 19 21 row4: 4 12 20 

 12345 row0: 0, 8, 16 row1: 1, 9, 17 row2: 2, 10, 18 row3: 3, 11, 19 row4: 4, 12, 20 

 123 row1: (1,7), (9,15), (17,23) row2: (2,6), (10,14), (18,22) row3: (3,5), (11,13), (19,21) 

 12345678910111213141516171819 class Solution: def convert(self, s, numRows): if numRows<=1 or numRows >= len(s): return s result = "" len_s = len(s) max_row_number = numRows-1 skip_mid_check = False for i in range(numRows): skip_mid_check = i == 0 or i == numRows-1 for n in range(i, len_s, 2 * max_row_number): result += s[n] if not skip_mid_check: next_idx = n + 2 * (max_row_number-i) if next_idx < len_s: result += s[next_idx] return result