您的位置:首页 > 职场人生

ZigZag Conversion

2015-07-16 19:38 288 查看
题目:
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。

代码如下:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息