Python刷leetcode--6.Z 字形变换

在这里插入图片描述

我的思路:

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        ans = ''
        if numRows == 1:
            return s
        for i in range(1, numRows + 1):  # i是从1到numRows+1
            step = i - 1
            ind = (numRows - 1) * 2 - (numRows - i) * 2
            while step < len(s):
                ans += s[step]
                if not (i == 1 or i == numRows):
                    ind = (numRows - 1) * 2 - ind
                else:
                    ind = (numRows - 1) * 2
                step += ind
        return ans

其他思路:

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        # leetcode submit region end(Prohibit modification and deletion)
        if numRows < 2:
            return s
        res = ["" for _ in range(numRows)]   # 行数个数组,分别记录每一行的字母
        i, flag = 0, -1  #
        for c in s:
            res[i] += c  # 一开始是0
            if i == 0 or i == numRows - 1:
                flag = -flag  # 第一个或者最后一个时,flag转向坐标向下变为向上
            i += flag  # 同上一步flag = -flag 这个是改变下标,那个是改变方向
        return "".join(res)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值