class Solution {
public String convert(String s, int numRows) {
StringBuilder[] sb = new StringBuilder[numRows];
for (int i = 0; i < sb.length; i++) {
sb[i] = new StringBuilder();
}
int i = 0;
while (i < s.length()) {
for (int j = 0; j < numRows && i < s.length(); j ++) {
sb[j].append(s.charAt(i));
i ++;
}
for (int k = numRows - 2; k > 0 && i < s.length(); k --) {
sb[k].append(s.charAt(i));
i ++;
}
}
StringBuilder res = new StringBuilder();
for (i = 0; i < sb.length; i++) {
res.append(sb[i]);
}
return res.toString();
}
}
Another submission accepted 05/12:
public class Solution {
public String convert(String s, int numRows) {
// Write your code here
if (numRows == 1) {
return s;
}
StringBuilder[] sbList = new StringBuilder[numRows];
for (int i = 0; i < sbList.length; i++) {
sbList[i] = new StringBuilder();
}
for (int i = 0; i < s.length(); i++) {
int mod = i % ((numRows - 1) * 2);
if (mod < numRows) {
sbList[mod].append(s.charAt(i));
} else {
sbList[(numRows - 1) * 2 - mod].append(s.charAt(i));
}
}
StringBuilder res = new StringBuilder();
for (StringBuilder sb : sbList) {
res.append(sb);
}
return res.toString();
}
}