Skip to content

6. ZigZag Conversion

难度: 中等

刷题内容

原题连接

  • https://leetcode.com/problems/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 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

解题方案

思路 1

参考大神pharrellyhy的思路, 纵向思维考虑,index0开始,我们要一直自增直到numRows-1,此后又一直自减0,重复执行。 给个例子容易懂一些:s = “abcdefghijklmn”, numRows = 4

a   g   m
b f h l n
c e i k
d   j

看明白了吗,下来上去,下来上去,zigzag

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
        res = [''] * numRows
        idx, step = 0, 1

        for x in s:
            res[idx] += x
            if idx == 0:  ## 第一行,一直向下走
                step = 1
            elif idx == numRows - 1: ## 最后一行了,向上走
                step = -1
            idx += step
        return ''.join(res)

假设用我上面给的例子,并且在L[index] += x这一行后面打印出index, step, L的值, 输出结果如下:

(0, 1, ['a', '', '', ''])
(1, 1, ['a', 'b', '', ''])
(2, 1, ['a', 'b', 'c', ''])
(3, 1, ['a', 'b', 'c', 'd'])
(2, -1, ['a', 'b', 'ce', 'd'])
(1, -1, ['a', 'bf', 'ce', 'd'])
(0, -1, ['ag', 'bf', 'ce', 'd'])
(1, 1, ['ag', 'bfh', 'ce', 'd'])
(2, 1, ['ag', 'bfh', 'cei', 'd'])
(3, 1, ['ag', 'bfh', 'cei', 'dj'])
(2, -1, ['ag', 'bfh', 'ceik', 'dj'])
(1, -1, ['ag', 'bfhl', 'ceik', 'dj'])
(0, -1, ['agm', 'bfhl', 'ceik', 'dj'])
(1, 1, ['agm', 'bfhln', 'ceik', 'dj'])


回到顶部