美文网首页
leetcode6. ZigZag Conversion

leetcode6. ZigZag Conversion

作者: 冰源 | 来源:发表于2018-09-10 12:27 被阅读7次
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 s, int numRows);
Example 1:
---
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
---
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
---
P     I    N
A   L S  I G
Y A   H R
P     I
Note:
---
1. 动态数组存储,整理后输出
2. [[] for row in range(3)] 与 [[]]*3的区别,后者有广播作用,更新[0]之后[1][2]也会更新
3. if numRows == 1: return s  # I forgot this
class Solution:
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows == 1: return s  # I forgot this
        rowlist = [[] for row in range(numRows)]  #numRows个动态数组存储zigzag
        list_length = 2*numRows - 2  #2*numRows - 2为一组
        for i in range(len(s)):
            idx = i%list_length
            if idx<numRows:
                rowlist[idx].append(s[i])  # 直下的数字
            else:
                rowlist[list_length-idx].append(s[i])  # 上拐的数字

        # 以下为整理操作,二维list变一维list,再变字符串输出
        res_list = rowlist[0]
        for j in range(1,numRows):
            res_list += rowlist[j]
        string = ""
        for char in res_list:
            string += char
        return string

相关文章

网友评论

      本文标题:leetcode6. ZigZag Conversion

      本文链接:https://www.haomeiwen.com/subject/sgwjgftx.html