ZigZag Conversion

Posted Chaz_Sun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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".

 解法:

技术分享图片
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)
c = Solution()
print c.convert("PAYPALISHIRING", 3)
View Code

1.通过索引和步长来解题,当走到头时,改变step的方向

 2. [""] * n 可以创建空字符列表。

以上是关于ZigZag Conversion的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode - 6 - ZigZag Conversion

ZigZag Conversion

ZigZag Conversion

leetcode06- ZigZag Conversion之Java版本

ZigZag Conversion

#Leetcode# 6. ZigZag Conversion