LEETCODE 0006

QUERY: 6. Zigzag Conversion
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”

PYTHON:
class Solution(object):
def convert(self, s, numRows):
“””
:type s: str
:type numRows: int
:rtype: str
“””
if numRows <= 1 or numRows >= len(s):
return s
arr = [”] * numRows
for i in xrange(len(s)):
tmp = i % (numRows + numRows – 2)
if tmp < numRows:
arr[tmp] += s[i]
else:
arr[numRows + numRows – 2 – tmp] += s[i]
return ”.join(arr)

Leave a comment

Design a site like this with WordPress.com
Get started