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"
.
Problem Description:
Gives a string and an integer numrows, returning the resulting zigzag sequence.
Workaround:
Find the law, draw the appearance when numrows=3,4,5,6, then find the law.
It is found that the starting position of each line is a late law, and the difference between Span=numrows + (numRows-2) character sequences is different from each other.
In the non-starting and end lines, each cycle needs to include an additional character, which differs from the starting character of this period by n = numrows + (numRows-2)-I * 2 characters.
The procedure is as follows:
Public classSolution { PublicString Convert (String s,intnumrows) { if(S.length () <=0 | | numrows<=1) returns; String Res= ""; intspan = NumRows + (numRows-2); for(inti=0; i<numrows; i++) {String S1=NewString (); for(intJ=i; J<s.length (); j=j+span) {S1= S1 +S.charat (j); intSpan1 = NumRows + (numRows-2) -2*i; if(i>0 && i<numrows-1 && j+span1<s.length ()) {//if it is an intermediate line, extra characters are requiredS1 = S1 + s.charat (j+span1); }} Res= Res +S1; } returnRes; }}
Leetcode--zigzag Conversion