Skip to content

Instantly share code, notes, and snippets.

@jingz8804
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jingz8804/9775595 to your computer and use it in GitHub Desktop.
Save jingz8804/9775595 to your computer and use it in GitHub Desktop.
public class ZigZagConversion {
public String convert(String s, int nRows) {
// corner cases
if(s == null) return null;
if(s.equals("")) return s;
if(nRows == 0) return null;
if(nRows == 1) return s;
StringBuilder[] builders = new StringBuilder[nRows];
for(int i = 0; i < nRows; i++){
builders[i] = new StringBuilder();
}
int nBetween = nRows - 2;
int len = s.length();
int count1 = 0;
boolean inBody = true; // e.g., when processing P A Y
int count2 = 0;
boolean inBetween = false; // e.g., when processing the single P in between
for(int i = 0; i < len; i++){
// pushing character to its corresponding builder
if(inBody == true && count1 < nRows){
builders[count1].append(s.charAt(i));
count1++;
}else if(inBetween == true && count2 < nBetween){
builders[nRows - 2 - count2].append(s.charAt(i));
count2++;
}
// state change between inBody and inBetween
if(inBody == true && count1 == nRows){
inBody = false;
inBetween = true;
count1 = 0;
}else if(inBetween == true && count2 == nBetween){
inBody = true;
inBetween = false;
count2 = 0;
}
}
StringBuilder b = new StringBuilder();
for(int i = 0; i < nRows; i++){
b.append(builders[i].toString());
}
return b.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment