# so easy to get it ! use array to solve zigzag

• we need get new string as line 0 ~line numRows, evey line chars is sequence. if we know string's every char's line number ,than we append the line from 0~numRows,we get the answer!
as:
String s ='0123456789ABCD'
numRows=4 (name R)

``````line=0      0                   6                  C
line=1      1            5     7           B        D
line=2      2     4            8    A
line=3      3                   9
``````

we need get this :
append( line 0).append(line 1).append(line 2).append(line 3)
so ,we need know every char's line number ,
notice that we put char from 0 to R,than we put next char at line R-1 ,than R-1-1,when we get the char at line 0,the loop begins again,
it like this :
lineArray : 0 1 2 3 2 1 0 1 2 3 2 1 0 1

s : 0 1 2 3 4 5 6 7 8 9 A B C D

just append line from 0 to R as lineArray .
code is here :
public String convert(String s, int numRows) {
if(numRows<=1)return s;
int[] a = new int[s.length()];//zi fu zuozai dehangshu
int step = 1;
for (int i = 1; i < a.length; i++) {
a[i] = a[i - 1] + step;
if (a[i] == numRows - 1) {
step = -1;
} else if (a[i] == 0) {
step = 1;
}
}
StringBuffer str = new StringBuffer();
for (int i = 0; i < numRows; i++) {
int j = 0;
while (j < a.length) {
if (a[j] == i) {
str.append(s.charAt(j));
}
j++;
}
}
return str.toString();
}

• format code :

``````public String convert(String s, int numRows) {
if (numRows <= 1) return s;
int[] a = new int[s.length()];
int step = 1;// up or down
for (int i = 1; i < a.length; i++) {
a[i] = a[i - 1] + step;
if (a[i] == numRows - 1) {
step = -1; //down
} else if (a[i] == 0) {
step = 1; // up
}
}
StringBuffer str = new StringBuffer();
for (int i = 0; i < numRows; i++) {
int j = 0;
while (j < a.length) {
if (a[j] == i) {
str.append(s.charAt(j));
}
j++;
}
}
return str.toString();
}

``````

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