Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created December 14, 2019 02:49
Show Gist options
  • Save shixiaoyu/89446e7303d5c213e64224d78ceb1fe6 to your computer and use it in GitHub Desktop.
Save shixiaoyu/89446e7303d5c213e64224d78ceb1fe6 to your computer and use it in GitHub Desktop.
public String convertSimulation(String s, int nRows) {
if (s == null || s.length() == 0 || nRows <= 0) {
return "";
}
if (nRows == 1) {
return s;
}
int size = s.length();
List<StringBuilder> buckets = new ArrayList();
for (int i = 0; i < nRows; i++) {
buckets.add(new StringBuilder());
}
int i = 0;
int index = 0;
boolean fromTopToBottom = true;
while (i < size) {
char c = s.charAt(i);
if (fromTopToBottom) {
if (index == nRows - 1) {
fromTopToBottom = false;
buckets.get(index).append(c);
index--;
} else {
buckets.get(index).append(c);
index++;
}
} else {
if (index == 0) {
fromTopToBottom = true;
buckets.get(index).append(c);
index++;
} else {
buckets.get(index).append(c);
index--;
}
}
i++;
}
String res = "";
for (StringBuilder sb : buckets) {
res += sb.toString();
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment