Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created December 14, 2019 02:50
Show Gist options
  • Save shixiaoyu/c1300a41e6cce8887eab55d6094348ba to your computer and use it in GitHub Desktop.
Save shixiaoyu/c1300a41e6cce8887eab55d6094348ba to your computer and use it in GitHub Desktop.
public String convertSimulationOptimizedImplementation(String s, int nRows) {
if (s == null || s.length() == 0 || nRows <= 0) {
return "";
}
if (nRows == 1) {
return s;
}
int size = s.length();
// directly allocate a string builder array
StringBuilder[] buckets = new StringBuilder[nRows];
for (int i = 0; i < nRows; i++) {
buckets[i] = new StringBuilder();
}
int i = 0;
int index = 0;
boolean fromTopToBottom = true;
while (i < size) {
char c = s.charAt(i);
buckets[index].append(c);
index += fromTopToBottom ? 1 : -1;
if (index == nRows - 1 || index == 0) {
fromTopToBottom = !fromTopToBottom;
}
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