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"
.
Test instructions is: give you a string, he is the string in the form of a Z-order, and then you read it in the form of a line. The number of rows given the string.
Problem solving: We find that the first and last lines are well handled, that is, each time you read j+2*nrows-2, the middle row needs to be handled separately.
As the above example, we found that we can process each constituency PAYP as a unit. is to choose a nrows+nrows-2=2nrows-2 length processing.
Then the positional relationship of the middle element is j+2*nrows-2i-2 (i means the first few lines)
OK, the code is as follows:
Public String Convert (string s, int nRows) {if (s = = NULL | | nRows = = 1) return s;int len = s.length (); if (len <= nRows) r Eturn s; StringBuffer res = new StringBuffer (); int size = 2 * nrows-2;//length of each processing for (int i = 0; i < nRows; i++) {//element of each row char C h;for (int j = i; J < len; j + = size) {ch = S.charat (j); res.append (ch); if (i! = 0 && I! = nRows-1) {//If it is an intermediate element Processing int tmp = j + size-2 * I;IF (tmp < len) {ch = s.charat (TMP); res.append (ch);}}} return res.tostring ();}
[Java]leetcode6 ZigZag Conversion