Leetcode6-ZigZag Conversion(Python3)

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

My Solution

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows == 1:
            return s
        r, dict_s = '', {}
        for i in range(len(s)):
            row = i % (numRows + numRows - 2)
            if row >= numRows:
                row = numRows + numRows - 2 - row
            if row in dict_s.keys():
                dict_s[row] = dict_s[row] + s[i]
            else:
                dict_s[row] = s[i]
        for i in range(max(dict_s.keys())+1):
            r = r + dict_s[i]
        return r

Reference (转)

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

        L = [''] * numRows
        index, step = 0, 1

        for x in s:
            L[index] += x
            if index == 0:
                step = 1
            elif index == numRows -1:
                step = -1
            index += step

        return ''.join(L)

你可能感兴趣的:(Leetcode6-ZigZag Conversion(Python3))