[Power button - small daily practice] 6. Z-shaped transform (python)

6. Z-shaped transform

Topic links: https://leetcode-cn.com/problems/zigzag-conversion/

Subject description:

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 "LEETCODEISHIRING"the number of lines is 3, arranged as follows:
Here Insert Picture Description

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);

Examples

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

Example 2:
Input: s = "LEETCODEISHIRING", numRows = 4
Output: "LDREOEIIECIHNTSG"

2 explains an example in which:
Here Insert Picture Description

Ideas:

Get the following results
Here Insert Picture Description
Here Insert Picture Description

Code

class Solution:
    def convert(self, s: str, numRows: int) -> str:
            result = []
            output = []
            column,i = 0, 0
            while i<len(s):
                tempt = numRows * ['*']
                for j in range(numRows):
                    if i + j < len(s):
                        tempt[j] = s[i + j]
                i += numRows
                column += 1
                result.append(tempt)
                tempt = numRows * ['*']
                for j in range(numRows-2):
                    if i < len(s):
                        tempt[-(j+2 % numRows)] = s[i]
                        i += 1
                        result.append(tempt)
                        tempt = numRows * ['*']
                        column += 1
            for t in range(numRows):
                for j in range(column):
                    char = result[j][t]
                    # print(char,end=' ')
                    if char != '*':
                        output.append(char)
                # print()
            return ''.join(output)
Published 44 original articles · won praise 5 · Views 4468

Guess you like

Origin blog.csdn.net/ljb0077/article/details/104724821