1 题目描述
2 解题思路
2.1 构造Z型数组
class Solution:
def convert(self, s: str, numRows: int) -> str:
if(numRows==1):
return(s)
#numRows=1 特判
tmp=[]
for i in range(numRows):
tmp.append([])
#Z型数组
i=0 #当前遍历到的s的下标
l=len(s)
index=0 #当前数组插入的状态
while(i<l):
if(index==0):
index=1
for j in range(numRows):
if(i<l):
tmp[j].append(s[i])
i=i+1
else:
break
#index=0——这一列都有值
elif(index==numRows-1):
index=0
#回到一开始index=0的状态,开始下一轮“循环”
else:
for j in range(numRows):
if(j!=numRows-1-index):
tmp[j].append(" ")
else:
tmp[j].append(s[i])
i+=1
index+=1
#每一列只有一个值非空
ret=""
for i in tmp:
for j in i:
if(j!=' '):
ret+=j
return(ret)
2.2 方法2 不模拟Z型数组
记返回的数组为res。
->按顺序遍历字符串 s;
->res[i] += c: 把每个字符 c 填入对应行
->i += flag: 更新当前字符 c 对应的行索引;
->flag = - flag: 在达到 Z 字形转折点时,更新步数执行反向。
class Solution:
def convert(self, s: str, numRows: int) -> str:
if(numRows==1):
return s
res = ["" for _ in range(numRows)]
i=0
flag=-1
for c in s:
res[i] += c
if (i == 0 or i == numRows - 1):
flag = -flag
#在达到 Z 字形转折点时,更新步数执行反向。
i += flag
return("".join(res))
可以看到,2.2的时间消耗比2.1小很多