题目描述:
https://leetcode-cn.com/problems/zigzag-conversion/
题解:
1.超时版
<1>定义一个shapez数组,大小为numRows*len(s),初始为全0
<2>从字符串s第一个元素开始写入shapez
<3>利用row col down right确定位置,将s[i]写入numRows[row][col],然后更新row=row+down col=col+right
<4>处理特殊情况:如果当前row=numRows-1 down=-1 right=1,向右上移动,如果row==0 down=1 right=0,重新开始向下移动
<5>读取shapez,将非0元素写入res
class Solution(object):
def convert(self, s, numRows):
if numRows==1:
return s
lens = len(s)
shapez = [[0 for m in range(lens)] for n in range(numRows)]
col = 0
row = -1
right = 0
down = 1
for i in range(lens):
row = row+down
col = col+right
shapez[row][col] = s[i]
if row == numRows-1:
down = -1
right = 1
if row == 0:
down = 1
right = 0
print(shapez)
res = ""
for i in range(numRows):
for j in range(lens):
if shapez[i][j]!=0:
res = res+shapez[i][j]
return res
2.改进版
直接将shapez定义为字符串
def convert(self, s, numRows): if numRows==1: return s lens = len(s) shapez = [""] *numRows row = -1 down = 1 for i in range(lens): row = row+down shapez[row] = shapez[row]+s[i] if row == numRows-1: down = -1 if row == 0: down = 1 res = "" for i in range(numRows): res = res+shapez[i] return res