首页 > 其他 > 详细

ZigZag Conversion

时间:2018-02-02 21:30:37      阅读:219      评论:0      收藏:0      [点我收藏+]

题目:

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

原文:https://www.cnblogs.com/jackzone/p/8406799.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!