LeetCode 6. ZigZag Conversion Python3
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);
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
问题分析
本题是一道中等题,题目的意思是给定一个字符串s和行数numRows,是按从上往下、从左往右的z字型排列的,现在需要你返回按行排列得到的字符串。
题目的意思很简单,在实现的过程中需要注意的就是控制好逻辑,我最开始的想法是设定一个二位数组,按照题目的要求去存储字符串,然后按行去遍历,得到的就是最后的结果,这样做可以满足要求,但就是效率不太高,代码如下:
class Solution:
def convert(self, s: str, numRows: int) -> str:
if not s:
return ""