码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode ZigZag Conversion C++ 解题思路

时间:2015-04-12 13:19:23      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

一个难度为Easy的题,看了好多人的题解都没想明白,最后使劲想使劲想,才想的差不多。。太弱了,要找不到工作了。。

题目描述:

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"

n=2

 0 2 4 6

 1 3 5 7

 n=3

 0     4     8

 1  3 5  7 9

 2     6    10 

 n=4时的走法是:

 0      6        12

 1   5 7    11 13

 2 4   8 10    14

 3      9         15 

这道题就是找规律题。

分析出每行的规律,然后拼凑在一起。

仔细观察可发现,一竖列和一斜列是一个周期,周期为2n-2,n是行数。一竖列有n个元素,一斜列第一行和最后一行没有元素所以为n-2个元素,所以加起来周期是2n-2个元素。每行相邻竖列上的元素的距离差别是一个周期,例如当n=4时,周期为2*4-2 = 6, 元素0和6相差6,元素1和7相差6。 

在中间的每一行,每两个竖列中间都有一个斜着排列的元素,例如1和7中间是5,7和13中间是11。中间的斜元素和前一个竖列上的元素相差为一个周期-2*行index。可以这样理解,例如,当n=4时,2的下一个周期的元素是8,则2和4的距离就是2到8的距离减去4到8的距离,2到8的距离是一个周期,4到8的距离是1+2+2+……+1,第一个1是第0行的元素,最后一个1是当前行(第i行)的那个元素(即8),中间每行有两个元素,因为i从0开始,所以总共有i个2。所以2到4的距离是2n-2 - 2i,如果2的位置是j,则4的位置是j+2n-2-2i,8的位置是j+2n-2.

 

代码如下:

 

string convert(string s, int nRows)
{
    if(s.length() == 0 || nRows<=0)
        return "";
    if(nRows == 1)
        return s;
    string res;
    int size = 2*nRows-2;
    for(int i = 0; i < nRows; i++)
        for(int j = i; j <s.length();j+=size)
        {
            res+=s[j];
            if(i!= 0 && i != nRows-1){
                int temp = j+size-2*i;
                if(temp < s.size())
                    res+=s[temp];
            }
        }
    return res;
    
}

 ref:[1]. http://www.cnblogs.com/springfor/p/3889414.html

    [2].http://blog.unieagle.net/2012/11/08/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Azigzag-conversion/

 

LeetCode ZigZag Conversion C++ 解题思路

标签:

原文地址:http://www.cnblogs.com/nily/p/4419351.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!