The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N A P L S I I G Y I R
And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows:
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
nRow = 2:
0 2 4 6 8 10 12
1 3 5 7 9 11 13
nRow = 3:
0 4 8 12
1 3 5 7 9 11
2 6 10
nRow = 4:
0 6 12
1 5 7 11 13
2 4 8 10
3 9
from the examples we can see the formula: from first non-zigzag column to next non-zigzag column, indexDiff = 2*nRows-2;
if not the first row and not the last row, the index difference between two char are columnIndexDiff = j+indexDiff-2*currRow
j is non zigzag column index
public String convert(String s, int nRows) {
if (s==null||s.isEmpty()||nRows<1) {
return "";
}
if (nRows==1) {
return s;
}
StringBuilder results = new StringBuilder();
int size = 2*nRows-2;
for(int i=0;i<nRows;i++) {
for(int j=i;j<s.length();j+=size) {
results.append(s.charAt(j));
//if not first and last row, we need to append the char in between.
int nextZig = j+size-2*i; //i is current row
if(i!=0 && i!=nRows-1 && nextZig<s.length()) {
results.append(s.charAt(nextZig));
}
}
}
return results.toString();
}