题目:
将字符串转为N型后按每行输出
示例:
输入:
LEETCODEISHIRING
输出:
L C I R
E T O E S I I G
E D H N
代码:
public class Test5 {
public static void main(String[] args) {
String s1 = "LEETCODEISHIRING";
String s2 = convert(s1,3);
System.out.println(s2);
}
public static String convert(String s, int numRows) {
if (numRows==1) {
return s;
}
char[] chars = s.toCharArray();
int rowLength = numRows;
int lineLength = s.length()/(2*numRows-1)*(numRows-1)+1;
Character[][] result = new Character[rowLength][1000];
int i = 0;
int rowIndex = 0;
int lineIndex = 0;
while(i<s.length()){
for(int j = 0;j<numRows && i<s.length();j++){
result[rowIndex][lineIndex] = chars[i];
rowIndex++;
i++;
}
rowIndex = rowIndex-2;
lineIndex=lineIndex+1;
for (int j =0;j<numRows-2 && i<s.length();j++){
result[rowIndex][lineIndex]=chars[i];
rowIndex--;
lineIndex++;
i++;
}
}
char[] resultChars = new char[chars.length+1];
int resutlIndex =0;
for (Character[] chars1 : result) {
for (Character c : chars1) {
if (c!=null) {
resultChars[resutlIndex++] = c;
}
}
}
return String.valueOf(resultChars);
}
}