【leetcode】ZigZag Conversion

来源:互联网 发布:0verture for mac 编辑:程序博客网 时间:2024/06/05 21:50

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"

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"

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

以上是题目。

       先来说说思路,可能有些同学不知道什么是zigzag.我举个栗子:

       1         7            13

       2      6 8        12

       3  5     9   11

       4         10

就是如上这些形式啦。

那么我们可以很显然的得出规律,不看斜的,每行数字之间的间隔是 n*2 - 2;n是行数。除了第一行和最后一行以外,其余各行中间会插一个数,然而这个数也是有规律的,这个数是j+n*2 -2 -2*I;j指的是插入这个数之前那个数,i表示目前在第i行,于是很容易得到以下代码。


class Solution {
public:
    string convert(string s, int numRows) {
        int len = s.length();
        if(len<2 || numRows == 1)return s;
        string arry;
        int t = 2*numRows-2;
        for(int i = 0;i<numRows;i++){
            for(int j = i;j<len;j+=t){
                arry.push_back(s[j]);
                if(i>0 && i<numRows-1 && j+t-2*i < len){
                    arry.push_back(s[j+t-2*i]);
                }
            }
        }return arry;
    }
};

1 0