Created
December 14, 2019 02:49
-
-
Save shixiaoyu/89446e7303d5c213e64224d78ceb1fe6 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 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