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 R
And 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”.
第一次看到这个题目的人,可能不知道ZigZag是什么意思,简单解释一下,就是把字符串原顺序012345……按下图所示排列:
这道题找规律即可,循环周期可能比较容易找,周期中间的规律 2 * nRows - 2 - 2 * i 可能不大好找。
public class Solution {
public String convert(String s, int nRows) {
int len = s.length();
if (len == 0 || nRows < 2) return s;
String ret = "";
int lag = 2*nRows - 2; //循环周期
for (int i = 0; i < nRows; i++) {
for (int j = i; j < len; j += lag) {
ret += s.charAt(j);
//非首行和末行时还要加一个
if (i > 0 && i < nRows-1) {
int t = j + lag - 2*i;
if (t < len) {
ret += s.charAt(t);
}
}
}
}
return ret;
}
}