欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

文巾解题 6. Z 字形变换

发布时间:2025/4/5 55 豆豆
生活随笔 收集整理的这篇文章主要介绍了 文巾解题 6. Z 字形变换 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

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=1for j in range(numRows):if(i<l):tmp[j].append(s[i])i=i+1else: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+=1index+=1 #每一列只有一个值非空ret=""for i in tmp:for j in i:if(j!=' '):ret+=jreturn(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 sres = ["" for _ in range(numRows)]i=0flag=-1for c in s:res[i] += cif (i == 0 or i == numRows - 1): flag = -flag#在达到 Z 字形转折点时,更新步数执行反向。i += flagreturn("".join(res))

可以看到,2.2的时间消耗比2.1小很多

总结

以上是生活随笔为你收集整理的文巾解题 6. Z 字形变换的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。