Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
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 code:
import numpy as np
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
length=len(s)
if length<=numRows:
return s
if numRows==1:
return s
batch=numRows*2-2
times=int(np.ceil(length/batch))
s1=""
for j in range(numRows):
for i in range(times):
if j==0:
index=i*batch+j
if index<len(s):
s1=s1+s[index]
elif j==numRows-1:
index=(i+1)*batch-(numRows-1)
#print(index)
if index<len(s):
s1=s1+s[index]
else:
index1=i*batch+j
#print(index1)
if index1<len(s):
s1=s1+s[index1]
index2=(i+1)*batch-(j)
#print(index2)
if index2<len(s):
s1=s1+s[index2]
return s1
Solution:
https://leetcode.com/problems/zigzag-conversion/