leetcode6 Zigzag Conversion

来源:互联网 发布:黑客大会 知乎 编辑:程序博客网 时间:2024/05/29 03:58

题目要求:

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   NA P L S I I GY   I   R

And then read line by line: "PAHNAPLSIIGYIR"

    采用坐标转换的方式来做这道题。我们现在以nRows=4来考虑,其实对于每一行,如果暂时不考虑中间的列,只考虑全满的列,则后面一个坐标都是前面的基础上加上2*(nRows-1),如0->6->12,1->7->13,2->8,3->9,因此,对于第i=0行和i=nRows行,直接按照这样的坐标转换读入,而对于中间行,每次按照这样的规律读入一个字符后,需要再追加一个字符,1->5,2->4。这个坐标转换的规律是什么呢,对于0->6,是一个nRows=4的zigzag,同理,对于1->5,2->4,则分别是nRows=3,nRows=2的zigzag,即,第i行,坐标增加的规律为前一个坐标的基础上增加2*(nRows-1-i)。


完整代码如下:


0 0
原创粉丝点击