首页 > 代码库 > leetcode ZigZag Conversion

leetcode 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".

 

分析:

  刚开始阅读没有理解问题的要求,以为每个偶数列都是只有一个字母。通过搜索查看别人的解题思路以及思考,明白 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