Question:
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)
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:
string convert(string s, int numRows);
Example1:
Input:s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example2:
Input:s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Mentality:
这道题实质上就是一道找规律题,规律如下:
- 第 0 行:k * 2 *(numRows-1);
- 第 n-1 行:k * 2 *(numRows-1)+(numRows-1);
- 内部 i 行:k * 2 * (n - 1) + i 以及(k + 1) * 2 * (n - 1) - i.
Code:
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
nlen = 2 * (numRows - 1)
news = ''
for i in range(numRows): #逐行遍历
j = 0
while j + i < len(s):
news += s[j+i]
if i not in [0,numRows-1] and j + nlen - i < len(s): #控制中间行
news += s[j+nlen-i]
j += nlen
return news
Result: