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"
.n=4
P I N
A L S I G
Y A H R
P I
N=5
P H
A S I
Y I R
P L I G
A N
The key points of this problem is to get the fact that:
- zigSize=2nRows-2
- In each zig, the index of the next element in between (in green) is index + (nRows-i-1)*2. For example, whenRow = 5, the current row=3, index(L) = index(P) + (5-3-1)*2=3+2=5;
No comments:
Post a Comment