思路
0 6 12
1 5 7 11 ..
2 4 8 10
3 9
观察可以得到,第一行和最后一行为公是2 * (numRows - 1)的等差数列,首项为0和numRows - 1;
对于中间的行,是两个公差为2 * (numRows - 1)的等差数列交替排列,首项为i和2 * numRows - i - 2;
代码
class Solution {
public String convert(String s, int numRows) {
if (s.isEmpty()) return "";
if (numRows == 1) return s;
String ans = "";
for (int j = 0; j < numRows; ++j) {
if (j == 0 || j == numRows - 1) {
for (int i = j; i < s.length(); i += (numRows - 1) * 2) {
ans += s.charAt(i);
}
} else {
for (int k = j, i = numRows * 2 - j - 2; i < s.length() || k < s.length(); i += (numRows - 1) * 2, k += (numRows - 1) * 2) {
if (k < s.length()) ans += s.charAt(k);
if (i < s.length()) ans += s.charAt(i);
}
}
}
return ans;
}
}