Tuesday, June 10, 2014

LeetCode (Python): 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 text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

We add another example to clarify, same string with 4 rows
P     I     N
A   L S   I G
Y A   H R   
P     I 
convert("PAYPALISHIRING", 4) should return "PINALSHIGYAHRPI"

Solution:

class Solution:
    # @return a string
    def convert(self, s, nRows):
        if nRows == 1:
            return s
        solution = []
        for i in range(0, nRows):
            count = i
            step1 = 2*(nRows-1-i)
            step2 = 2*i
            while count < len(s):
                solution.append(s[count])
                if step1 > 0 and step2 > 0 and count+step1<len(s):
                    count += step1
                    solution.append(s[count])
                    count += step2
                else:
                    count +=(step1+step2)
        return "".join(solution)

1 comment :