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"
.
三行: 四行:
之字形排列的一道题,这道题自己想了一个方法发现对最后一个散组的处理比较麻烦。参考了网上的算法,实现了一个简便的算法。
这道题是一道找规律的题。如上面的例子: 首行跟尾行的规律比较好找。相邻两个相差 2*nRow - 2。 而在剩余行,同一行相邻元素也是有规则的。nRow = 3 时, 第二行中 3跟1之间差: 2*nRow -2 - 2;nRow = 4 时, 第二行中 5 跟1之间差2*nRow -2 -2, 第三行中 4跟2 之间差2 *nRow-2 -4。依次类推。规则找到了,在非首行跟尾行,除了周期固定有一个数,中间还有一个数字,并且规律跟当前行数有关系。若当前行为i,那么相邻元素的位置为 2*nRows-2 - 2*i 。
补充:
代码如下:
public String convert(String s, int nRows){
int len = s.length();
if(len==0 || nRows <2 ) return s;
String res = "";
int lag = 2*nRows-2;
//循环行数这么多就好
for(int i=0;i<nRows;i++){
for(int j = i;j<len;j+=lag){
res += s.charAt(j);
//非首行跟尾行 中间要加一个
if(i>0 && i < nRows -1){
int temp = j+ lag-2*i;
//从当前位置j 位置起后面 2*nRow-2-2*i 还有一个数字
//注意如果没有一个满的周期会报出数组越界
if(temp <len)
res += s.charAt(temp);
}
}
}
return res;
}