Leetcode - 6 Z字形变换 python

版权声明:本文章为原创,未经许可不得转载 https://blog.csdn.net/weixin_41864878/article/details/90478410

将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。

比如输入字符串为 “LEETCODEISHIRING” 行数为 3 时,排列如下:

L C I R
E T O E S I I G
E D H N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“LCIRETOESIIGEDHN”。

请你实现这个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);
示例 1:

输入: s = “LEETCODEISHIRING”, numRows = 3
输出: “LCIRETOESIIGEDHN”
示例 2:

输入: s = “LEETCODEISHIRING”, numRows = 4
输出: “LDREOEIIECIHNTSG”
解释:

L D R
E O E I I
E C I H N
T S G

列表查表

首先找规律,numRows行的z字形,如下图分解
在这里插入图片描述

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if not s or len(s) <= 2: return s
        if numRows == 1:return s 
        #s = s.split('"')[0]
        length = 2 * (numRows - 1)
        k = len(s) // length
        n = len(s) % length #余数部分的讨论
        i = -1
        out = [None] * k if n == 0 else [None] * (k+1) #多余的一行记录不能完整构成一个单位的部分
        #构造out列表
        for i in range(k):
            out[i] = s[length*i: length*(i+1)]
        if n: out[k] = s[length * (i+1):len(s)]
        
        res = ''.join([out[j][0] for j in range(len(out))]) #先读第一行,就是out中每一列的第一个字母
        for i in range(1, numRows-1):
            if n != 0:
                res += ''.join([out[j][i] + out[j][length - i] for j in range(len(out)-1)]) #再按索引依次读,中心线就是index=numRows
                if n > length-i: res += out[len(out) - 1][i] + out[len(out) - 1][length-i]
                elif n > i: res += out[len(out) - 1][i]
            elif n == 0: res += ''.join([out[j][i] + out[j][length - i] for j in range(len(out))])
            
        res += ''.join([out[j][numRows-1] for j in range(len(out)-1)])# 读最下面一行,每行只有一个字母
        if n > numRows-1: res += out[len(out) - 1][numRows-1]
        elif n == 0: res += out[len(out)-1][numRows-1]
        return res

本来以为这个蠢蠢的算法会是超时错误 结果居然过了hhhh
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41864878/article/details/90478410