Leetcode 6. ZigZag Conversion

Description: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);

Link: 6. ZigZag Conversion

Examples:

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

Example 3:
Input: s = "A", numRows = 1
Output: "A"

题意理解: 我刚看到这个题,完全不理解什么意思。题意是说给定一个字符串s,把s按照N字形锯齿排列,然后按行输出。这个题解对怎么N排列有详细的例子,很容易懂,理解了是怎么排列的很容易做了。接下来就是找每一行字母下标的规律,第一行和最后一行,每个元素的间隔是numRows + (numRows-2),竖的一画需要numRows个元素,和斜的连接两个竖的,要消耗numRows - 2, 所以到下一个中间隔了interval = 2×numRows - 2和元素。中间的每一行间隔是interval-2*row, interval - (interval-2*row), 两个竖的间距是不变的,总是interval, 中间插入的这个元素的index和所处的行row有关。所以知道了每一行的排列规律,从第一行依次输出就好了。

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows == 1: return s
        res = ''
        interval = 2*numRows-2
        for i in range(0, len(s), interval):
            res += s[i]
        for l in range(1, numRows-1):
            i = l
            inter = 2*l
            while i < len(s):
                res += s[i]
                inter = interval - inter
                i += inter
        for i in range(numRows-1, len(s), interval):
            res += s[i]
        return res

日期: 2021-04-04 清明节,那边也复活节放假了

原文地址:https://www.cnblogs.com/wangyuxia/p/14616741.html