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);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
python代码 z有numRows行,按指定的循环顺序往z的行里添加元素,最后把z的不同行合并起来,顺序由rn这个列表规定
k和j控制添加的次数,还有i也是控制添加的次数。
class Solution:
def convert(self, s: 'str', numRows: 'int') -> 'str':
if numRows==1:
return s
n=numRows
z=['']*n
rn=list(range(0,n-1))+list(range(n-1,0,-1))
slen=len(s)
i=0
for k in range(slen//(2*n-2)+1):
for j in range(2*n-2):
z[rn[j]]+=s[i]
if i==(slen-1):
return "".join(z)
else:
i=i+1