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:
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:
Ideas:
Get the following results
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)