ZigZag Conversion(Z型字符串转换)

ZigZag Conversion(Z型字符串转换)

2 min read

问题描述

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               | /     | /     |

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

P     A     H     N         |     / |     / |
A  P  L  S  I  I  G         |   /   |   /   |
Y     I     R               | /     | /     |

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"

P       I       N        |      / |     / |
A    L  S    I  G        |     /  |    /  |
Y  A    H  R             |   /    |   /   |
P       I                | /      | /     |

解题思路

找规律,会发现下图所示的规律:
2020-08-24 231536
n=4时,原始字符串每一个字符的编号总是0,1,2,3,2,1的循环,所以只需要遍历一遍原始字符串,给每一个字符标号就行了。

Python实现

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        res = [[] for i in range(numRows)]
        idx = list(range(numRows))+list(range(numRows-2,0,-1))
        for i,ch in enumerate(s):
            res[idx[i%len(idx)]].append(ch)
        return ''.join([''.join(i) for i in res])

前一篇

括号生成问题

后一篇

将图片格式转成EPS格式