006.ZigZag Conversion

Solution 1:

In this question we need to rearrange a string according to certain order. We need to find out the order of rearrangement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public static String convert(String s, int numRows) {
if (numRows < 2 || s == null || s.length() < numRows)
return s;
StringBuilder sb = new StringBuilder();
int circleLength = 0;
if (numRows < 3)
circleLength = numRows;
else
circleLength = numRows * 2 - 2;
for (int i = 1; i <= numRows; i++) {
for (int j = 1; j <= s.length(); j++) {
if (j % circleLength == i) {
sb.append(s.charAt(j - 1));
}
if (i == 2 && j % circleLength == 0) {
sb.append(s.charAt(j - 1));
}
if (i > 2 && i != numRows && j % circleLength == circleLength - i + 2) {
sb.append(s.charAt(j - 1));
}
}
}
return sb.toString();
}

Solution 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public String convert(String s, int nRows) {
int len = s.length();
if (len == 0 || nRows < 2) return s;
String ret = "";
int lag = 2*nRows - 2; //循环周期
for (int i = 0; i < nRows; i++) {
for (int j = i; j < len; j += lag) {
ret += s.charAt(j);
//非首行和末行时还要加��?��?
if (i > 0 && i < nRows-1) {
int t = j + lag - 2*i;
if (t < len) {
ret += s.charAt(t);
}
}
}
}
return ret;
}