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"
.
这道题题目给的不太明白,容易让不清楚ZigZag的人一头雾水,下面这个大家已看应该就清楚了
Zigzag:即循环对角线结构(
0 |
|
|
| 8 |
|
|
| 16 |
1 |
|
| 7 | 9 |
|
| 15 | 17 |
2 |
| 6 |
| 10 |
| 14 |
| 18 |
3 | 5 |
|
| 11 | 13 |
|
| 19 |
4 |
|
|
| 12 |
|
|
| 20 |
)
向下循环:nRows
斜角线循环:nRows-2(减去首尾两个端点)
重复
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public
class
Solution {
public
String convert(String s,
int
numRows) {
StringBuffer sb =
new
StringBuffer();
if
(numRows<
2
){
return
s;
}
else
{
//两列直接的对角线元素为numRows-2;因此定义两列之间的步长
int
step =
2
*(numRows-
1
);
for
(
int
row=
0
;row<numRows;row++){
//按照步长将第row行的非对角线元素添加进StringBuffer
for
(
int
j=row;j<s.length();j+=step){
sb.append(s.charAt(j));
//当第row行不是首行和尾行,且增加步长之后的索引在长度范围内时,将对角线上的元素添加到StringBuffer
if
((row!=
0
&&row!=numRows-
1
)&&(j+step-row*
2
)<s.length()){
sb.append(s.charAt(j+step-row*
2
));
}
}
}
return
sb.toString();
}
}
}
|