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 RAnd then read line by line:
"PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)
should
return "PAHNAPLSIIGYIR"
.Analysis:
public class Solution {
public String convert(String s, int nRows) {
if(nRows==1) return s;
StringBuilder res = new StringBuilder();
int acc = 2*nRows-2; // nRows==1 -> acc=0, infinite loop
int[] diff = new int[nRows];
for(int i=0; i<nRows; i++) {
if(i==0 || i==nRows-1) diff[i]=acc;
else diff[i]=acc-i*2;
}
for(int j=0; j<nRows; j++) {
int first=diff[j], second=diff[diff.length-1-j], k=j;
boolean odd = true;
while(k < s.length()) {
res.append(s.charAt(k));
if(odd) {
k += first;
odd = false;
}
else {
k += second;
odd = true;
}
}
}
return res.toString();
}
}