# Question explanation and 8ms Java solution, beats 73%

• The question asks us to place the characters of a string in a zigzag pattern and read the string line by line. Here is an example.

``````a     (g)     k   (g)    u
b          j  l       t  v
c (g-d) i (d) m     s    w
d    h        n   r      x
e g           o q        y
f             p          z
``````

And we should return "akubjltvcimswdhnrxegoqyfpz". Now you must know what the zigzag pattern is. ('g' for "gap", 'd' for "diff" and "g-d" for "gap - diff").

``````    public String convey(String s, int numRows) {
if (s == "")
return "";
if (numRows == 0 || numRows == 1)
return s;
StringBuilder res = new StringBuilder();
int gap = 2 * (numRows - 1);
int diff = 0;
for (int i = 0; i < numRows; i++) {
int countPos = 0;
for (int j = i; j < s.length();) {
res.append(s.charAt(j));
// If it is in the first line and the last line
if (diff == 0 || i == numRows - 1)
j += gap;
else{
// If countPos is a even number, move to the next (gap - diff) position
if (countPos % 2 == 0)
j += (gap - diff);
// If countPos is an odd number, move to the next diff position
else
j += diff;
countPos ++;
}
}
diff += 2;
}
return res.toString();
}``````

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