topic
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
Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/zigzag-conversion
Thinking
Directly open a list of two-dimensional simulation.
Code
class Solution:
def convert(self, s: str, numRows: int) -> str:
l=len(s)
if l==1 or numRows==1:
return s
lie=l//(numRows*2-2)*(numRows-1)
yu=l%(numRows*2-2)
if yu<=numRows:
lie+=1
else:
lie=lie +1 +yu-numRows
ans=[['']*lie for _ in range(numRows)]
i=0
hang,x,y=0,0,0
#print(ans)
while(i<l):
if hang<numRows:
ans[hang][x]=s[i]
hang+=1
if hang==numRows:
x+=1
y=numRows-2
elif y!=0:
ans[y][x]=s[i]
y-=1
x+=1
if hang==numRows and y==0:
hang=0
i+=1
res=""
for ll in range(numRows):
for hh in range(lie):
if ans[ll][hh]!=' ':
res=res+ans[ll][hh]
return res