首页 > 其他 > 详细

leetcode ZigZag Conversion

时间:2017-07-08 16:34:18      阅读:201      评论: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".

 

分析:

  刚开始阅读没有理解问题的要求,以为每个偶数列都是只有一个字母。通过搜索查看别人的解题思路以及思考,明白 zigzag是这种形式

  

"PAYPALISHIRING" 字符串分为4行时
P       I       N
A    L  S    I  G
Y  A    H  R
P       I 

实现代码为

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
        zigzag = [[] for x in range(numRows)]
        row, step = 0, 1
        for c in s:
            zigzag[row] += c,
            if row == 0:
                step = 1
            elif row == numRows - 1:
                step = -1
            row += step
        return ‘‘.join(reduce(operator.add, zigzag))

注意点:

  python中列表的这种形式 zigzag[row] += c;默认把右边的‘c‘值转为了列表形式;不能改写为zigzag[row] + c形式

  reduce(operator.add,zigzag)实现对zigzag立面的每个列表值加起来,比如[[1,2,3],[4,5,6]] 计算后结果为[1,2,3,4,5,6]

leetcode ZigZag Conversion

原文:http://www.cnblogs.com/virtue/p/7137129.html

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