The string"PAYPALISHIRING"Is written in 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 line by line:
"PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)Shocould return"PAHNAPLSIIGYIR".
Description:
Input data in the Word format and output data horizontally.
.
Solution:
Set n to the number of input rows, and I to the number of rows.
Observe the Image Search rules.
If the distance between 0th lines and the last line is 2 * N-2
If it is an intermediate line, if the row and column number is an even number and the next character is 2 * (n-i-1), otherwise if it is an odd number and the next character is 2 * I
For example:
As shown in the figure, there are 1st rows, the first character is 1, the column number is 0, an even number, and the distance from the second is 2 * (5-1-1) = 6
That is, the next character is 6 + 1 = 7
Because the character column number of 7 is 3, the distance between the column numbers of the next character is 2*1 = 2, that is, 7 + 2 = 9.
Public class solution {Public String convert (string S, int nrows) {string res = ""; int Len = S. length (); If (nrows <= 1 | Len = 0 | Len <nrows) // determines whether the number of rows and the length of characters do not match return S; for (INT I = 0; I <nrows; I ++) {int Index = I; Res + = S. charat (INDEX); Boolean flag = true; // even for (int K = 0; index <Len; k ++) {if (I = 0 | I = nRows-1) // use Formula 1 {index + = 2 * nrows-2 ;} else {// The intermediate number uses the formula 2 if (FLAG) // even {index + = 2 * (nRows-1-i); flag = false;} else {index + = 2 * I; flag = true ;}} if (index <Len) // determines whether the threshold is exceeded. If the threshold is not exceeded, add res + = S. charat (INDEX) ;}} return res ;}}
Leetcode zigzag Conversion