public String convert(String s, int numRows) {
if (numRows <= 1) {
return s;
}
int n = s.length();
int step = 2 * numRows  2;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numRows; i++) {
for (int j = i; j < n; j += step) {
sb.append(s.charAt(j));
if (i != 0 && i != numRows  1 && j + step  2 * i < n) {
sb.append(s.charAt(j + step  2 * i));
}
}
}
return sb.toString();
}
In fact, this is a math problem, JAVA code.


This is the best solution. Efficient and easy to digest.
See my c++ version
class Solution { public: string convert(string s, int numRows) { if(1==numRows){ return s; } int N=s.size(); string result(s); int p=0; int steps = 2*numRows2; int lastRowIdx=numRows1; for(int i=0;i<numRows;i++){ for(int j=i;j<N;j+=steps){ result[p++]=s[j]; if(i>0 && i<lastRowIdx){ int jj = j+(lastRowIdxi)*2; if(jj<N) result[p++]=s[jj]; } } } return result; } };