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 ""
if numRows == 1:
return s
col =(len(s) // (numRows + numRows - 2) + 1) * (numRows - 1)
res = [[""] * col for _ in range(numRows)]
k = 0
flag = False
for i in range(col):
if i % (numRows - 1) == 0:
for j in range(numRows):
res[j][i] = s[k]
k += 1
if k == len(s):
flag = True
break
if flag:
break
else:
res[numRows - 1 - (i % (numRows - 1))][i] = s[k]
k += 1
if k == len(s):
break
result = ''.join(''.join(res[i]) for i in range(numRows))
return result
通过阅读评论区的优秀解法,可以发现这道题背后有规律,在遍历字符串s的时候,可以通过设置一个变量,来控制当前字符应该属于哪一行,当属于最后一行的时候,把控制变量设为-1,这样就可以依次往索引小的行移动,当到达第0行的时候,设置控制变量为1,这样就可以依次往索引大的方向移动。如果你没有理解的话,那就先看看代码实现吧,通过代码应该能帮助你理解。
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1 or numRows >= len(s):
return s
res = [''] * numRows
row, step = 0, 0
for temp in s:
res[row] += temp
if row == 0:
step = 1
if row == numRows - 1:
step = -1
row += step
return ''.join(res)
运行结果对比
从图中可以看出,二者的运行时间相差还是很大的,所以善于学习才能不断进步,提高。
ok!大功告成了,如果你有其他的方法或者问题,欢迎在评论区交流。