6. Z 字形变换|Python|LeetCode

在这里插入图片描述

思路一

呜呜呜我想了半天,左右打补丁结果还是到处漏风wwwT^T,还是贴上来记录下,原因是没有考虑下面这种情况
在这里插入图片描述
我的思路有点像这个,6. Z 字形变换 找规律解决,附详细代码介绍

class Solution:
    def convert(self, s: str, numRows: int) -> str:

        if len(s) == 1 or numRows == 1 or len(s) <= numRows:
            return s

        res = [] # to avoid creating the futile string, update it until the ending
        reslist = [] # first record the index of the result
        Kthnumber = 0 # record the current index
        r, c = 0, 0 # record the circle number
        base = 0 # record the number of the first row as the basis
        i = 0

        # get the first row as the basis
        print('lens', len(s))
        while True:
            Kthnumber = r * (2 * numRows - 2) + 1 # th
            print(Kthnumber)
            if  Kthnumber > len(s):
                break
            reslist.append(Kthnumber - 1) # update the index
            base += 1
            r += 1 

        print(reslist)
        print('base', base)
        # seemingly, base, r have the identical meaning

        # like binary tree 
        print('numRows', numRows)
        while True: # cow
            c += 1 
            print(c)
            if c == numRows:
                break
            while True:                
                Kthnumber = reslist[i]

                i += 1

                right = Kthnumber + c
                left = Kthnumber - c

                if c < numRows - 1: # in the last cow, avoid the duplicate , so only record the right
                    if left >= 0: reslist.append(left) 

                if right < len(s): reslist.append(right) 

                if i == base :
                    i = 0
                    break
        
        # convert index to str
        for i in reslist:
            res.append(s[i])
        
        print(''.join(res))
       # assert "PAHNAPLSIIGYIR" == ''.join(res)

        return ''.join(res)

思路二

看了其他解析,才发觉许多精妙之处,细节可看Z 字形变换(清晰图解)

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if len(s) == 1 or numRows == 1: # 特殊情况
            return s

        res = [[] for _ in range(numRows)]  # 每一行一个list
        i = 0
        flag = -1
        for char in s: # 遍历字符串,行方向移动res数组,接收字符
            res[i].append(char)
            if i == numRows - 1 or i == 0: flag = -flag # Z型转弯角,换移动方向
            i += flag
        # 汇总1
        for i in range(numRows):
            res[i] = "".join(res[i])
        # 汇总2
        return "".join(res)

让我想到了单摆沙漏,底下纸以垂直方向匀速运动,可成正弦运动形状。
换个思维,移动参照物,效果更佳。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值