Implimentation:
index+unitsize - 2*row
public String convert(String s, int nRows) {
//Boundary condition
if (s==null || s.length()==0 || nRows <=0) return "";
if (nRows==1) return s;
//Traverse the whole string, chopped the string as different unit
//The unit size should be 2*nRows - 2
//In each unit, the first column is easy to handle.
//The second column need to use index + Unitsize - 2 * row
int unitSize = 2*nRows - 2;
StringBuilder result = new StringBuilder();
for (int i=0; i<nRows; i++) {
for (int j = i; j < s.length(); j+=unitSize) {
result.append(s.charAt(j));
if (i!=0 && i!=nRows-1 && j+unitSize-2*i<s.length()) {
result.append(s.charAt(j+unitSize-2*i));
}
}
}
return result.toString();
}
No comments:
Post a Comment