LeetCode ZigZag Conversion, leetcodezigzag
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 ;}}
C ++ returns a string? Why have I tested both dev c ++ and vc60? But cannot it be used in leetcode?
The Runtime Error does not mean that your program cannot be compiled, but that your program encountered an Error during running. This error is generally caused by out-of-bounds array access, stack overflow, and illegal memory access.