[Leetcode] [Python] ZigZag Conversion

Source: Internet
Author: User

#-*-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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.