6. N 字形变换

该文章描述了一个Python类方法,用于将输入字符串按照Z字形(也称锯齿形)排列。方法首先初始化一个二维数组,然后遍历输入字符串,根据特定规则将字符填充到数组中。最后,将数组中的行合并成一个字符串返回。
摘要由CSDN通过智能技术生成

题目描述

 方法:

创建numRow行数组保存z字

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if numRows==1 or not s:
            return s
        n = len(s)
        record = [[] for i in range(numRows)]
        i,j  = 0,-1
        flag = 1
        while i < n:
            if flag and j < numRows-1:
                j += 1
            elif flag and j == numRows-1:
                flag = 0

            if not flag and j>0:
                j -= 1
            elif not flag and j == 0:
                j += 1
                flag = 1

            record[j].append(s[i])
            i += 1
        
        res = []
        for line in record:
            res += line
        return "".join(res)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值