来自北大算法课的Leetcode题解:6. Z字形变换

代码仓库Github | Leetcode solutions @doubleZ0108 from Peking University.

  • 解法1(T11% S5%):纯数组逻辑题。首先开辟一个足够大的二维空间,用题目中不会出现的字符填充,按照题干首先往下走(top→bottom),然后斜着向上走(torighttop),每走一步把一个字母放到对应的位置上,遇到上下边界就换方向,最终一次二维扫描组装最后的结果。唯一需要注意的是只有1行的时候要单独考虑,直接返回原字符串就好
    • 改进1(T29% S14%):空间状态压缩。注意到二维矩阵中有大量空间都是填充的垃圾值且之后输出时还要多判断一次,而且还不知道要开辟多少列,因此可以每行用一个链表来存结果,每走到新位置就在该行链表的结尾添加一个值
  • 解法2:其实可以有严格的数学对应关系,这里略
class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        # 解法1 改进1
        if numRows == 1 or len(s)<=numRows: return s

        themap = [[] for _ in range(numRows)]
        i, j = 0, 0
        dir = "top->bottom"
        for idx in range(len(s)):
            themap[i].append(s[idx])
            if idx == len(s)-1: break

            if dir=="top->bottom":
                if i == numRows-1:
                    i -= 1
                    j += 1
                    dir = "torighttop"
                else:
                    i += 1
            elif dir=="torighttop":
                if i == 0:
                    i += 1
                    dir = "top->bottom"
                else:
                    i -= 1
                    j += 1

        res = ""
        for i in range(numRows):
            for k in range(len(themap[i])):
                res += themap[i][k]
        
        return res

    def otherSolution(self, s, numRows):
        # 解法1
        if numRows == 1 or len(s)<=numRows: return s

        themap = [['@']*len(s) for _ in range(numRows)]
        i, j = 0, 0
        dir = "top->bottom"
        for idx in range(len(s)):
            themap[i][j] = s[idx]
            if idx == len(s)-1: break

            if dir=="top->bottom":
                if i == numRows-1:
                    i -= 1
                    j += 1
                    dir = "torighttop"
                else:
                    i += 1
            elif dir=="torighttop":
                if i == 0:
                    i += 1
                    dir = "top->bottom"
                else:
                    i -= 1
                    j += 1

        res = ""
        for i in range(numRows):
            for k in range(j+1):
                if themap[i][k] != "@":
                    res += themap[i][k]
        
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

doubleZ0108

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

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

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

打赏作者

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

抵扣说明:

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

余额充值