Leetcode Zigzag Conversion problem solution in Python programming

In the Leetcode Zigzag Conversion problem solution in Python programming 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);

Leetcode Zigzag Conversion problem solution in Python programming

class Solution(object):
    def convert(self, s, numRows):
        if numRows<2:
            return s
        lst = ['']*numRows
        step = 1
        index = 0
        for i in s:
            if index == numRows:
                step = -1
                index -= 2
            if index == -1:
                step = 1
                index +=2
            lst[index] = lst[index] + i
            index += step
        return ''.join(lst)

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *