Leetcode (6) Z-shaped transform
[Topic expressed]:
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:
L C I R
E T O E S I I G
E D H N
After that, you need the output from left to right read line by line, produce a new string, such as: "LCIRETOESIIGEDHN".
First: find standard output row under the law
When execution: 84 ms; memory consumption: 11.8MB Effect: OK
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
res=""
List=[]
#一组是2*numRows-2个
#len(s)<numRows
s_number,Aqueue=len(s),2*numRows-2
if len(s)==0 or Aqueue==0:
return s
queue_number=s_number/Aqueue
Yushu=s_number-queue_number*Aqueue
for i in range(1,numRows+1):
List.append("")
for j in range(0,queue_number):
if i==1 or i==numRows:
List[i-1]+=s[i+Aqueue*j-1]
else:
List[i-1]+=s[i+Aqueue*j-1]
List[i-1]+=s[i+Aqueue*j-1+(numRows-i)*2]
if Yushu>=i:
List[i-1]+=s[i-1+s_number-Yushu]
if (i+(numRows-i)*2)<=Yushu and i!=numRows:
List[i-1]+=s[i-1+s_number-Yushu+(numRows-i)*2]
res+=List[i-1]
return res
Learn
- To find the law, using the output string of characters stored in the list of each row
The second method: I · Z character string in the line output
When execution: 80 ms; memory consumption: 13.2MB effects: Very good
class Solution:
def convert(self, s: str, numRows: int) -> str:
L = ['' for x in range(numRows)]
n = 0
flag = True
for i in s:
if n > numRows - 2:
flag = False
elif n <= 0:
flag = True
L[n] += i
if flag:
n += 1
else:
n -= 1
return ''.join(L)
Learn
Press Z word go, as a group, and n the number of cursors, flag as a mark that the current is walking or foldback
Better than I thought
['' for x in range(numRows)] ''.join(L)