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)
1 2 3
P A H N A P L S I I G Y I R
And then read line by line:
1
"PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
int n = s.length(); int t1 = numRows; int t2 = numRows - 2; int k = n / (t1 + t2) + 1;
// 初始化 char[][] c1 = newchar[k][t1]; char[][] c2 = newchar[k][t2]; for (int i = 0; i < k; i++){ for (int j = 0; j < t1; j++) c1[i][j] = '_'; for (int j = 0; j < t2; j++) c2[i][j] = '_'; }
// 分为两个部分 for (int i = 0; i < k; i++) { int index = i * (t1 + t2); for (int j = 0; j < t1+t2; j++){ if (index + j < n){ if (j < t1) c1[i][j] = s.charAt(index+j); else c2[i][t2-1-(j-t1)] = s.charAt(index+j); } } }
// 格式输出 String result = ""; for (int i = 0; i < numRows; i++){ for (int j = 0; j < k; j++){ if (c1[j][i] != '_') result += c1[j][i]; if (i > 0 && i < numRows-1 && c2[j][i-1] != '_') result += c2[j][i-1]; } }
近期评论