BiruLyu
5/24/2017 - 6:17 PM

## 6. ZigZag Conversion.java

``````
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
res = "";
if not s:
return res;

if numRows == 1 or len(s) <= numRows :
return s;

l = numRows;
temp = 0;
while(temp < len(s)):
res += s[temp];
temp += l + l - 2;
for i in range(1, numRows - 1): # except the fist and the last row, each row add character :Odd-even alternation
res += s[i];
#col = 1;
j = i;
col = 0;
while(j < len(s)):

diff = ((l - 1) - i) + ( ( l - 2 ) - i ) + 1;
j = j + diff;
if (j < len(s)):
res += s[j];
diff = ( (i - 1) + ( i - 0) + 1);
j = j + diff;
if (j < len(s)):
res += s[j];

temp = l - 1;
while(temp < len(s)):
res += s[temp];
temp += l + l - 2;

return res;

"""

"0123456789" | "0123456789"  ### Note:if numRows > len(s): return s;
11           |
"0123456789" | "0481357926"
3            |
"0123456789" | "0615724839"
4            |
"0123456789" | "0817926354"
5            |
"0123456789" | "0192837465"
6            |
""           | ""
0            |
"""
``````
``````public class Solution {
public String convert(String s, int numRows) {
//String res = "";
if(s == null || s == "" || numRows == 1) return s;
//String[] eachRow = new String[numRows];
StringBuilder[] eachRow = new StringBuilder[numRows];
for (int i = 0; i < eachRow.length; i++) eachRow[i] = new StringBuilder();// Initialization!!!!
int direct = -1;
int j = 0;
for(int i = 0; i < s.length(); i++){
if(j == 0 || j == numRows - 1 ){
direct *= -1;
}
eachRow[j].append(s.charAt(i));
j += direct;
}
for(int i = 1; i < numRows; i++){
eachRow[0].append(eachRow[i]);
}
return eachRow[0].toString();
}
}``````