文巾解题 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=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小很多

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UQI-LIUWJ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值