将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。
第二个例子:
输入:s = “PAYPALISHIRING”, numRows = 4
输出:“PINALSIGYAHRPI”
解释:
P I N
A L S I G
Y A H R
P I
链接:https://leetcode-cn.com/problems/zigzag-conversion
首先,我自己的一个解题思路,比如根据第二个例子创建个二维列表,如下:
P A Y P
0 L A 0
I S H I
0 I R 0
N G 0 0
输出时,按列从上到下输出,0不输出,即可。
实现代码如下,耗时64ms,15.1mb:
class Solution:
def convert(self, s: str, numRows: int) -> str:
c = len(s)
x = []
i = 0
new_s = []
if numRows*2-2>0:
while c !=0:
if c>=numRows*2-2:
x.append(list(s[i:i+numRows]))
temp = [0]*numRows
temp[1:-1] = list(s[i+numRows:i+numRows*2-2])
x.append(temp[::-1])
c = c-numRows*2+2
i = i+numRows*2-2
elif c>=numRows:
x.append(list(s[i:i+numRows]))
temp = [0]*numRows
end = c-numRows
temp[1:1+end] = list(s[i+numRows:])
x.append(temp[::-1])
c = 0
else:
temp = [0]*numRows
temp[0:c] = list(s[i:])
x.append(temp)
c = 0
for j in range(len(x[0])):
for i in range(len(x)):
if x[i][j] !=0:
new_s.append(x[i][j])
else:
new_s.append(s)
return ''.join(new_s)
评论区看到一个大佬的思想非常好,只用了几行。
主要思想就是设置了flag。
开始i=0,
res[0]=res[0]+s[0],
flag = 1,
i=i+flag=1
直到 i 为numrows-1,开始换方向,flag=-1
此时i依次递减,还是从s中顺序往后取,但是倒序存在res里。为大佬思想点赞。
res[0] = P A Y P
res[1] = L A
res[2] = I S H I
res[3] = I R
res[4] = N G
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows < 2: return s
res = ["" for _ in range(numRows)]
i, flag = 0, -1
for c in s:
res[i] += c
if i == 0 or i == numRows - 1: flag = -flag
i += flag
return "".join(res)
链接:https://leetcode-cn.com/problems/zigzag-conversion/solution/zzi-xing-bian-huan-by-jyd/
本文介绍了一种将字符串以Z字形方式排列并重新组合的方法。通过实例展示如何使用Python来实现这一转换,并提供了一种高效简洁的解决方案。
733

被折叠的 条评论
为什么被折叠?



