码迷,mamicode.com
首页 > 其他好文 > 详细

ZigZag Conversion

时间:2018-02-02 21:54:08      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:for   索引   src   span   列表   on()   isp   ext   hid   

题目:

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

标签:for   索引   src   span   列表   on()   isp   ext   hid   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!