ZigZag Conversion

题目:

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.首先需要知道ZigZag的形式,是一种Z型的结构;

   2.特例nRows分别为2,3,4,5时,画出相应的图,从而找到每一行元素的关系;

   3.通过观察:  (1)第一行和最后一行两个元素之间相差(2*nRows-2);

                            (2)中间行:第一列设为k=1,观察得到,奇数列两个数之间差为2*(nRows-1-i);

                                                 偶数列两个数差为2*i。


代码如下:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章