Topic:
The string is "PAYPALISHIRING"
written with a zigzag pattern on a given number of rows like this: (You may want to display this pattern In a fixed font for better legibility)
P A H NA p L S i i GY i R
And then read on 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"
.
Links: https://leetcode.com/problems/zigzag-conversion/
A brush
Python
First calculate the number of peaks in S, and then two rounds of circulation, the outer cycle for numrows, the internal cycle for the peak quantity, each step is calculated on the left and right sides respectively whether valid, each group trough the range of left open to close.
Algorithm boundary condition is too many, runtime only beat less than 10%
classsolution (object):defconvert (self, S, numrows):""": Type S:str:type numRows:int:rtype:str""" ifLen (s) <= NumRowsorNumRows = = 1: returns Num_group= (Len (s) + numRows-1)//(2 * (numRows-1)) + 1Zigzag_chars= [] forRowinchRange (numrows): forIinchRange (num_group): Left_index= 2 * (numRows-1) * I-Row Right_index= 2 * (numRows-1) * i +RowifLeft_index >= 0 andLeft_index <Len (s):ifLeft_index% (2 * (numRows-1))! = 0 andLeft_index% (numRows-1) = =0:Pass Else: Zigzag_chars.append (S[left_index])ifLeft_index! = Right_index andRight_index <Len (s): Zigzag_chars.append (S[right_index])return "'. Join (Zigzag_chars)
6. ZigZag Conversion