LeetCode第六题(ZigZag Conversion)

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”.


Python代码:

class Solution:
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if len(s) <= numRows or numRows == 1:
            return s
        step = numRows * 2 - 2
        ret = s[::step]     #处理第一行
        for i in range(1, numRows-1):       #第i行
            for j in range(i, len(s), step):    #第j列
                ret +=s[j]
                if j + (step - i * 2) < len(s):
                    ret += s[j + (step - i * 2)]
        ret += s[numRows - 1::step]     #处理最后一行
        return ret

总结:主要考察字符串操作,思路是找出ZigZag转换的规律,确定转换前后下标间的关系,然后就可以直接得出结果了。

猜你喜欢

转载自blog.csdn.net/ax478/article/details/79860343