ZigZag Conversion
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".
解答:
该题目是一道找规律数学题,第一行和最后一行,每个数字中间间隔为2*numrows-2, 中间行的规律为:x+y=(2*numrows-2)*k (k为行数)
按行查找,时间复杂度 o(n)
//Runtime: 7 ms o(n)
public static String convert(String s, int numRows) {
int len = s.length();
if (len <= numRows || numRows == 1) {
return s;
}
StringBuilder sb = new StringBuilder();
// 单独处理第一行
for (int i = 0; i < len; i += (2 * numRows - 2)) {
sb.append(s.charAt(i));
}
// 处理除第一行和最后一行的行
for (int i = 1; i < numRows - 1; i++) {
for (int j = i, k = 1; j < len; j = k * (2 * numRows - 2) - j, k++) {
sb.append(s.charAt(j));
}
}
// 处理最后一行
for (int i = numRows - 1; i < len; i += (2 * numRows - 2)) {
sb.append(s.charAt(i));
}
String result = sb.toString();
return result;
}