# 7ms Java Solution (beat 91%)

• For example the below 5 (r) rows

suppose a b c d e of indices 0,1,2,3,4

Then from, note that there are two step sizes alternation

``````a -> i,  only step size = (r-1-0)*2
b -> h, step size1 = (r-1-1)*2, step size2 = 1*2
c -> g, step size1 = (r-1-2)*2, step size2 = 2*2
d -> f, step size 1 = (r-1-3)*2, step size2 = 3*2
e -> m, only step size = (r-1-0)*2 = (r-1-(4%(r-1)))*2
``````

Then you get the patterns, ;-), use StringBuilder saves time significantly for very long string!

``````a       i
b     h j
c   g   k   ....
d f     l n
e       m
``````

``````public class Solution {
public String convert(String s, int numRows) {
if(numRows==1) return s;
StringBuilder sb = new StringBuilder();
int r = numRows - 1;
for(int i = 0; i < numRows; i++) {
int step1 = (r-i%r)*2; // this can never be ZERO!
int step2 = (i%r)!=0 ? (i%r)*2 : step1;
int step=step2; // let it switch to step1 later
for(int j=i; j<s.length();j+=step) {
sb.append(s.charAt(j));
step = step==step1 ? step2 : step1; // alternate steps
}
}
return sb.toString();
}
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.