Created
February 16, 2020 02:14
-
-
Save wushbin/0a7953d0493637b83d5980c5b1c1c5af to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
Solution One | |
Two Pass | |
**/ | |
class Solution { | |
public String convert(String s, int numRows) { | |
if (s == null || s.length() == 0 || numRows == 0) { | |
return ""; | |
} | |
if (numRows == 1) { | |
return s; | |
} | |
StringBuilder[] rows = new StringBuilder[numRows]; | |
for (int i = 0; i < numRows; i++) { | |
rows[i] = new StringBuilder(); | |
} | |
int idx = 0; | |
int len = s.length(); | |
while(idx < len) { | |
for (int i = 0; i < numRows && idx < len; i++,idx++) { | |
rows[i].append(s.charAt(idx)); | |
} | |
for (int i = numRows - 2; i > 0 && idx < len; i--, idx++) { | |
rows[i].append(s.charAt(idx)); | |
} | |
} | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i < numRows; i++) { | |
sb.append(rows[i]); | |
} | |
return sb.toString(); | |
} | |
} | |
/** | |
Solution Two | |
One Pass | |
**/ | |
class Solution { | |
public String convert(String s, int numRows) { | |
if (s == null || s.length() == 0 || numRows == 0) { | |
return ""; | |
} | |
if (numRows == 1) { | |
return s; | |
} | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i < numRows; i++) { | |
int prej = -1; | |
int j = i; | |
int[] steps = {2 * (numRows - i - 1), 2 * i}; | |
int stepIdx = 0; | |
while(j < s.length()) { | |
if (prej != j) { | |
sb.append(s.charAt(j)); | |
} | |
prej = j; | |
j += steps[stepIdx]; | |
stepIdx = 1 - stepIdx; | |
} | |
} | |
return sb.toString(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment