The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N A P L S I I G Y I RAnd then read line by line:
"PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR"
定义二维数组,根据java的特性,全部值为0,根据特点可以得出规律
public static String convert(String s, int numRows) {
//用于存放结果
String result="";
//当行数为1的时候要返回原来的字符串
if(numRows==1){
return s;
}
//若是空或者为“”就直接返回“”
if(s!=null && !("".endsWith(s))){
char[] charArray = s.toCharArray();
int length = charArray.length, flag=0;
//定义最大的数组
int cols = (length/(numRows*2-2))*(numRows-1)+(numRows-1);
char[][] rowCols = new char[cols][numRows];
for(int i = 0; i < cols && flag < length; i++ ){
if(i%(numRows-1) == 0){
for(int j = 0; j < numRows && flag < length; j++ ){
rowCols[i][j]=charArray[flag++];
}
}else{
if(flag < length){
rowCols[i][numRows-1-(i%(numRows-1))]=charArray[flag++];
}
}
}
for(int i = 0; i < numRows; i++ ){
for(int j = 0; j < cols; j++ ){
if(rowCols[j][i] != 0){
result+=rowCols[j][i];
}
}
}
}
return result;
}
本文介绍了一种将字符串以Z字形排列并按行读取的算法实现。通过定义二维数组来模拟字符串在不同行间的交错填充过程,最终按行拼接成新的字符串。文章提供了详细的Java代码实现。

被折叠的 条评论
为什么被折叠?



