Skip to content

Instantly share code, notes, and snippets.

@junminstorage
Last active February 21, 2016 03:17
leetcode zigzag string
public String convert(String s, int numRows) {
if(s==null || s.isEmpty() || s.length() == 1 || numRows <= 1)
return s;
int len = s.length();
int numCols = getNumCols(len, numRows);
char[][] matrix = new char[numRows][numCols];
for(int i=0; i<len; i++){
matrix[getNumRows(i+1, numRows)-1][getNumCols(i+1, numRows)-1] = s.charAt(i);
}
StringBuilder sb = new StringBuilder();
for(int r=0; r<numRows; r++){
for(int c=0; c<numCols; c++){
if(matrix[r][c]!='\0')
sb.append(matrix[r][c]);
}
}
return sb.toString();
}
public int getNumRows(int len, int numRows){
int t = len%(numRows-2+numRows);
if(t==0)
return 2;
else if(t>numRows)
return 2+numRows-2+numRows-t;
else
return t;
}
public int getNumCols(int len, int numRows){
int t1 = len/(numRows-2+numRows);
int t2 = len%(numRows-2+numRows);
if(t2==0)
return t1*(numRows-1);
else if(t2>numRows)
return t1*(numRows-1) + t2 - numRows + 1;
else
return t1*(numRows-1) + 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment