题目

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)

1
2
3
P   A   H   N
A P L S I I G
Y I R

And then read line by line:

1
"PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

1
string convert(string text, int nRows);
1
convert("PAYPALISHIRING", 3)

should return

1
"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
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public:
string convert(string s, int numRows) {
string res = "";
if (numRows == 1||s.size()<=numRows)
return s;
int len =s.size();
int row =0;
int groupnumber = 2*numRows-2;
for(int row=0;row<numRows;row++)
{
if(row==0)
{
for(int i = 0;i<len;i=i+groupnumber)
{
res = res+s[i];
}
}
else if(row==numRows-1)
{
for(int i=numRows-1;i<len;i=i+groupnumber)
{
res =res+s[i];
}
}
else
{
for(int i=0;i<len;i=i+groupnumber)
{
if(i+row<len) res = res+s[i+row]; // 注释1
if(i+groupnumber-row<len) res = res+s[i+groupnumber-row];
}
}
}
return res;
}
};

思路

首先要求z子型输出,其实可以把拐弯的地放都看成直的。

1
2
3
4
5
A       B      Y            A   A   A
B A D T R A A A A A
C A R R Y ======> A A A A A 看成这种形状比较方便,也好写代码。
D A T F Q A A A A A
E Y Y A A A

一行一行的输出,首先根据行数可以计算出一个group的个数,比如上面的图中一个PAYP就是一个group,然后就是以一个group为一个循环。首先判断,字符串长度没有行数长时,就可以直接输出。

接着是for循环,分为三部分,第一行,最后一行,中间行,分别进行输出。

需要特别注意的是注释1的地方,注释1上面的for循环只确保了i<len,并没有确保i+row<len 所以加一个if判断,否则会输出乱码。