Leetcode - 6 Z-shape converting python

Disclaimer: This article is original, All Rights Reserved https://blog.csdn.net/weixin_41864878/article/details/90478410

The number of a given string according to the given row, to down, left to right from the Z-shaped arrangement.

Example, the input string is the number of rows "LEETCODEISHIRING" is 3, arranged as follows:

LCIR
ETOESIIG
EDHN
After that, you need the output from left to right read line by line, produce a new string, such as: "LCIRETOESIIGEDHN".

You will realize this string conversion function specified number of lines:

string convert (string s, int numRows );
Example 1:

Input: s = "LEETCODEISHIRING", numRows = 3
Output: "LCIRETOESIIGEDHN"
Example 2:

Input: s = "LEETCODEISHIRING", numRows = 4
Output: "LDREOEIIECIHNTSG"
explanation:

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

List look-up table

First find the law, z-shaped with numRows, as exploded
Here Insert Picture Description

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

Originally I thought that this stupid stupid algorithm is actually the result of a timeout error after hhhh
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/weixin_41864878/article/details/90478410