#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
https://oj.leetcode.com/problems/zigzag-conversion/
The string "Paypalishiring" is written with a zigzag pattern on a given number of rows like this:
(Want to display the this pattern in a fixed font for better legibility)
P A H N
A P L S i i G
Y I R
And then read line: "Pahnaplsiigyir"
Write the code that would take a string and make this conversion given a number of rows:
String convert (string text, int nRows);
Convert ("Paypalishiring", 3) should return "Pahnaplsiigyir".
===comments by dabay===
Use the nrows array to accept each character.
When nrows equals 1 o'clock, it returns s directly.
When nrows is greater than or equal to 2 o'clock, the nrows array is defined,
2*nrows-2 is a loop. From the first line to the last line, and then back to the second row from the penultimate line.
Use the mold to determine the position,
When it is less than or equal to nRows-1, it is placed directly into the corresponding array of modules.
When it's bigger than nRows-1, here's the math problem:
Mod-(nRows-1) is the number of rows that should go up, the last line is labeled NRow-1, so this line should be: (nRow-1)-(mod-(nRows-1)) =2*nrows-mod-2
‘‘‘
Class Solution:
# @return A string
def convert (self, S, nRows):
if nRows = = 1:
return s
Array2D = []
For-N in range (0, nRows):
Array2d.append ([])
For I in range (0, Len (s)):
MoD = i% (2*nrows-2)
If mod <= nRows-1:
Array2d[mod].append (S[i])
Else
x = 2*nrows-mod-2
Array2d[x].append (S[i])
val = ""
For-N in range (0, nRows):
For V in Array2d[n]:
val = val + V
Return Val
def main ():
s = solution ()
Print S.convert ("paypalishiring", 3)
if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python] ZigZag Conversion