Arrange a string "PAYPALISHIRING"
into a zigzag into a given number of lines:
Then read characters line by line from left to right:"PAHNAPLSIIGYIR"
Implement a function that transforms a string with a specified number of lines:
Example 1:
Example 2:
package LeetCode; public class A6Z glyph transform { public String convert(String s, int numRows) { if (numRows == 1) { return s; } else { int n = ((numRows - 1) > 0) ? (numRows - 1) : 1; // n numbers are a set of subscripts starting from 0 // if(isEven((s.length()-1)/n)){ // int[][] G = new int[numRows][(s.length()-1)/2]; // }else { // int[][] G = new int[numRows][(s.length()-1)/2+(s.length()-1)%2]; // } char[][] G = new char[numRows][(s.length() - 1) / 2 + n]; int row = 0; int line = 0; String resString = new String(); for (int i = 0; i < s.length(); i++) { int quotient = i / n; int remiander = i % n; if (isEven(quotient)) { row = remiander; line = quotient / 2 * n; } else { row = n - remiander; line = quotient / 2 * n + remiander; } G[row][line] = s.charAt(i); } for (int i = 0; i < G.length; i++) { for (int j = 0; j < G[i].length; j++) { // System.out.println(G[i][j]); if (G[i][j] != ' ') { resString += G[i][j]; } } } return resString; } } private boolean isEven(int i) { // TODO Auto-generated method stub if (i % 2 == 0) { return true; } return false; } public static void main(String[] args) { // String s = "PAYPALISHIRING"; // String s = "A"; String s = "AB"; int numRows = 1; A6Z Glyph Transform a6z Glyph Transform = new A6Z Glyph Transform(); System.out.println(a6z glyph transform.convert(s, numRows)); } }This code runs fine in eclipse, but the result of execution in LeetCode is this:
Code execution result:
my input
"PAYPALISHIRING" 3
my answer
"P\u0000A\u0000H\u0000N\u0000APLSIIG\u0000Y\u0000I\u0000R\u0000\u0000\u0000"
expected answer
"PAHNAPLSIIGYIR"
Execution time: 0 ms
It shows that the original judgment still counts empty characters, so make some changes to the code, put! =' ' to ! =', u0000'
if (G[i][j] != '\u0000') {
resString += G[i][j];
}