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 N A P L S I I G Y 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 s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I
题解:
这道题就是看坐标的变化。并且需要分块处理。
n=2时,字符串坐标变成zigzag的走法就是:
0 2 4 6
1 3 5 7
n=3时的走法是:
0 4 8
1 3 5 7 9
2 6 10
n=4时的走法是:
0 6 12
1 5 7 11 13
2 4 8 10 14
3 9 15
可以发现规律,画红色的长度永远是 2n-2
用二维数组存放Z字变换之后的字符,只需找出字符串对应字符下标与其在二维数组中位置的规律即可。
代码:
//ZZC -- Z字形变换 public static String getZZC(String s , int numRows){ if(numRows == 1){ return s; } char[] c = s.toCharArray(); //将一连串的Z按照的上中部重新划分 int zNum = 2*numRows-2; int len = c.length; int ySize = (len/zNum+1)*(numRows-1); char[][] zzc = new char[numRows][ySize]; for (int i = 0; i < len; i++) { int ax = i%zNum , ay = (i/zNum)*(numRows-1); int bx = numRows - (i%zNum-numRows+1)-1 , by = (i/zNum)*(numRows-1)+(i%zNum)-numRows+1; if(i%zNum<numRows){ zzc[ax][ay] = c[i]; } if(i%zNum>=numRows){ zzc[bx][by] = c[i]; } } String res = ""; for (int i = 0; i < numRows; i++) { for (int j = 0; j < ySize; j++) { System.out.print(zzc[i][j]+" "); if(zzc[i][j]!='\u0000'){ res += zzc[i][j]; } } System.out.println(""); } System.out.println(res); return res; }