将字符串 "PAYPALISHIRING"
以Z字形排列成给定的行数:
之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"
实现一个将字符串进行指定行数变换的函数:
示例 1:
示例 2:
package LeetCode; public class A6Z字形变换 { public String convert(String s, int numRows) { if (numRows == 1) { return s; } else { int n = ((numRows - 1) > 0) ? (numRows - 1) : 1; // n个数为一组 下标从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字形变换 a6z字形变换 = new A6Z字形变换(); System.out.println(a6z字形变换.convert(s, numRows)); } }这段代码在eclipse里运行没问题,但是在LeetCode里执行的结果是这样的:
代码执行结果:
我的输入
"PAYPALISHIRING" 3
我的答案
"P\u0000A\u0000H\u0000N\u0000APLSIIG\u0000Y\u0000I\u0000R\u0000\u0000\u0000"
预期答案
"PAHNAPLSIIGYIR"
执行用时:0 ms
说明原来的判断还是把空的字符给算进来了,所以要对代码做一点修改,把 !=‘ ’ 改成 !=‘、u0000’
if (G[i][j] != '\u0000') {
resString += G[i][j];
}