For the input string, make a serpentine change and then output by line.
https://oj.leetcode.com/problems/zigzag-conversion/
For example: The Serpentine change of the string "Paypalishiring" is as follows:
P A H N
A P L S i i G
Y I R
The final demand for output is: "Pahnaplsiigyir"
Write the code that would take a string and make this conversion given a number of rows:
Convert ("Paypalishiring", 3) should return "Pahnaplsiigyir".
Problem-solving ideas: Seemingly can be obtained by the method of pushing the formula, we still use the program simulation method to obtain the results.
Using the program, initialize the character array of a column row, and then follow the rules to multibyte each word of the original string to the corresponding line until the end of the string.
Take the string "paypalishiring" for example, "Pay P ALI S HIR I NG", new character array matrix[3]
Then, matrix[0] = matrix[0] + "P"; MATRIX[1] = matrix[1] + "A"; MATRIX[2] = matrix[2] + "Y";
MATRIX[1] = matrix[1] + "P";
Matrix[0] = matrix[0] + "A"; MATRIX[1] = matrix[1] + "L"; MATRIX[2] = matrix[2] + "I";
MATRIX[1] = matrix[1] + "S";
Matrix[0] = matrix[0] + "H"; MATRIX[1] = matrix[1] + "I"; MATRIX[2] = matrix[2] + "R";
MATRIX[1] = matrix[1] + "I";
Matrix[0] = matrix[0] + "N"; MATRIX[1] = matrix[1] + "G";
Each string of the last output column: Pahn AplsiigYir , we get the final result.
public class Solution {public string convert (String s, int nRows) { if (s.length () ==1| | nrows==1) {<span style= "white-space:pre" ></span>return s;} stringbuffer[] Matrix = new Stringbuffer[nrows];int i = 0, end = nRows-2, index = 0;for (i=0;i<nrows;i++) {<span St Yle= "White-space:pre" ></span>matrix[i] = new StringBuffer ("");} while (Index<s.length ()) {//extends <span style= "White-space:pre" ></span>for (I=0;index<s.length () &&i<= (nRows-1); i++) {Matrix[i].append (S.charat (index++));} Diagonal extension, i.e. up for (End=nrows-2;index<s.length () &&end>0;end--) {matrix[end].append (S.charat (index++)) ;}} StringBuffer result = new StringBuffer (""); for (int a=0;a<nrows;a++) {result.append (Matrix[a]);} System.out.println ("result=" +result.tostring ()); return result.tostring ();} }
Leetcode ZigZag Conversion problem Solving report