(Medium #6) ZigZag Conversion
Problem
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
My solution
class Solution:
def convert(self, s: str, numRows: int) -> str:
fig = []
for i in range(numRows):
fig.append('')
if numRows==1:
return s
else:
for i in range(len(s)):
modnum = numRows-1
if i%(modnum*2) < modnum:
fig[i%modnum] += s[i]
else:
fig[modnum-i%modnum] += s[i]
result = ''
for i in range(len(fig)):
result += fig[i]
return result
def convert(self, s: str, numRows: int) -> str:
fig = []
for i in range(numRows):
fig.append('')
if numRows==1:
return s
else:
for i in range(len(s)):
modnum = numRows-1
if i%(modnum*2) < modnum:
fig[i%modnum] += s[i]
else:
fig[modnum-i%modnum] += s[i]
result = ''
for i in range(len(fig)):
result += fig[i]
return result
댓글
댓글 쓰기