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"
.
解題思路:
1.首先需要知道ZigZag的形式,是一種Z型的結構;
2.特例nRows分別爲2,3,4,5時,畫出相應的圖,從而找到每一行元素的關係;
3.通過觀察: (1)第一行和最後一行兩個元素之間相差(2*nRows-2);
(2)中間行:第一列設爲k=1,觀察得到,奇數列兩個數之間差爲2*(nRows-1-i);
偶數列兩個數差爲2*i。
代碼如下: