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" .
First understand the test instructions, give a string, according to the glyph (Zigzag) arranged into a rectangle, each line of the matrix is joined together to form a string.
Compress the matrix to get:
1 #-*-coding:utf-8-*-2 3 classsolution (object):4 defconvert (self, S, numrows):5 """6 : Type S:str7 : Type Numrows:int8 : Rtype:str9 """Ten ifNumRows = = 1: One returns AZigzag = ["' forIinchRange (NumRows)]#initialize zigzag to [', ', ', '] -Row = 0#Current number of columns -Step = 1#number of steps: Control Data input the forCinchS: - ifrow = =0: -Step = 1 - ifrow = = NumRows-1: +Step =-1 -Zigzag[row] + =C +Row + =Step A return "'. Join (Zigzag)
Leetcode6:zigzag [email protected]