6. ZigZag Conversion
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"
.
N=4 the way to go is:
0 6 12
1 5 7) 11 13
2 4 8) 10 14
3 9 15
Solution:
For the first and last row, the interval is 2*n-2.
For the median diagonal line, the interval is the current column j+ (2n-2) -2i (i is the row).
Java implementations:
1 PublicString Convert (String s,intnRows) { 2 if(s = =NULL|| S.length () ==0 | | NRows <=0) 3 return""; 4 if(NRows = = 1) 5 returns;6 7StringBuilder res =NewStringBuilder (); 8 intSize = 2*nrows-2; 9 for(inti=0;i<nrows;i++){ Ten for(intJ=i;j<s.length (); j+=size) { One Res.append (S.charat (j)); A if(I! = 0 && I! = nRows-1) {//except the first row and the last row - inttemp = j+size-2*i; - if(temp<s.length ()) the res.append (S.charat (temp)); - } - } - } + returnres.tostring (); -}
"Java" 6. ZigZag Conversion