leetcode 6 ZigZag变换

题目:

将字符串’PAYPALISHIRING'以Z字型排列成给定的行数,然后逐行读取字符:
例子:
行数为3
P  A   H   N
A P L S I I G
Y    I   R
输出:
'PAHNAPLSIIGYIR'

例如第二行的,P L,他们是字符串的第3,5,此时row是2x3-2=4,那么可以看出 3 % 4 = 3, 5 % 4 = 1,3 + 1 = 4 = 2 numrows -2 。他们都属于a[1],所以可以用2numRows - 2 - row,来求出3的行数。

#python3
class Solution:
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows == 1:
            return s
        a = ['' for i in range(numRows)] #建立一个numrows的数组,用来存放每一行
        for i in range(len(s)):
            row = i % (2*numRows - 2)
            if row >= numRows:
                row = 2*numRows - 2 - row #!!!
            a[row] += s[i]
        return ''.join(a) #a=[PAHN,APLSIIG,YIR]