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"
.
把第一行和最后一行拿出来单独处理 i指向行
其他行可以发现规律如下
从0---7是一个拐角 每个拐弯有2n-2个数
j指向每个拐角的第i行第一个数 如 i=1时 j = i step j = j + 2n-2 如图 j = 1,9……
剩下就是如何插入7了,通过观察可以看出7的位置是2*(n-2-i) 即在j和7中间有多少个数,除却最后一行的4以及7本身,中间剩下的为n-2-i行,每行2个数,故此位置可用j+2*(n-2-i)得出
Source
public class Solution {
public static String convert(String s, int nRows) {
int i = 0, j, cnt = 0,k;
StringBuffer a = new StringBuffer(); //string没有append类
if(s == null || s.length() <= nRows || nRows <= 1) return s; //注意这几种特殊情况
for(i = 0; i < s.length(); i = i + 2 * nRows - 2) //每个拐弯是2n-2个字符 处理第一行
a.append(s.charAt(i)); //append用于在字符串末尾添加新字符
for(i = 1; i < nRows - 1; i++) //中间行按行分别处理
{
for(j = i; j < s.length(); j = j + 2 * nRows -2) //每个拐弯的这个位置
{
a.append(s.charAt(j));
if(j + 2 * nRows - 2 - 2 * i < s.length())
{
a.append(s.charAt(j + 2*nRows - 2 - 2 * i));
}
}
}
for(i = nRows -1; i < s.length(); i = i + 2 * nRows - 2) //处理最后一行
a.append(s.charAt(i));
return a.toString(); //将stringbuffer转换为string
}