Created
December 14, 2019 02:50
-
-
Save shixiaoyu/c1300a41e6cce8887eab55d6094348ba to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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