Contents
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*
* 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".
*/

直接模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {  
public:
string convert(string s, int nRows) {
if (nRows == 1)
return s;
//step = (nRows - 1) * 2
int step = nRows * 2 - 2, len = s.length();
string ret = "";
//第一行
for (int i = 0; i < len; i += step)
ret += s[i];
//中间行
for (int i = 1; i < nRows - 1; i++) {
for (int j = i; j < len; j += step) {
ret += s[j];
if (j + (step - i * 2) < len)
ret += s[j + (step - i * 2)];
}
}
//最后一行
for (int i = nRows - 1; i < len; i += step)
ret += s[i];
return ret;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class ZigZagConversion {
public String convert(String s, int nRows) {
if (nRows == 1)
return s;
String res = "";
int len = s.length();
int T = 2 * nRows - 2;
for (int i = 0; i < nRows; i++) {
for (int j = 0; i + j * T < len; j++) {
res += s.charAt(i + j * T);
if (i > 0 && i < nRows - 1 && (T - i + j * T < len))
res += s.charAt(T - i + j * T);
}
}
return res;
}
}
Contents