LeetCode 6: 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”.

题目举的例子不够明显,我们用数字,做一个4行的图形更容易分析。

0 - - 6 - - 12
1 - 5 7 - 11 13
2 4 - 8 10 - 14
3 - - 9 - - 15

首先我们观察到间隔着有些列是完整的,我们按照完整行对字符串进行分段组,每组具有numRows+numRows-2个元素。

继续观察,每一个分组中,第一行和最后一行都只有一个元素,而其余各行都有两个元素,两个元素的间隔offset = 2*numRows-row-row-2.于是我们得到如下的代码:

class Solution {
public:
  string convert(string s, int numRows){
        size_t len = s.size();
        string result;
        if(len <= numRows|| numRows ==1)
            return s;
        int groupLen = 2*numRows -2;
        for(int row=0; row<numRows; row++){
            if (row==0 || row== numRows-1) {
                for (int i=row; i<len; i+= groupLen) {
                    result.push_back(s[i]);
                }
            }else{
                int offset = 2*numRows -2 -2 *row;
                for (int i=row; i<len; i+=groupLen) {
                    result.push_back(s[i]);
                    if(i+offset <len)
                        result.push_back(s[i+offset]);
                }
            }
        }
        return result;
    }
};

上面这段代码虽然能够被AC,但是,但中间那个if-else显得很丑陋,其实row=0时,offset=2*numRows-2,就是下一次分割的第一个元素。row=numRows-1时,offset=0,就是本身。这样可以将那个if-else合并起来,不过仍然注意避免越界。得到下面的代码,这个看起来要美观一点:

class Solution {
public:
  string convert(string s, int numRows){
          size_t len = s.size();
        string result;
        if(len <= numRows|| numRows ==1)
            return s;
        int groupLen = 2*numRows -2;
        for (int row=0; row<numRows; row++) {
            int offset = 2*numRows -2 -2*row;
            for(int i=row; i<len; i+=groupLen){
                result.push_back(s[i]);
                if(offset!=0 && offset!=groupLen && i+offset<len){
                    result.push_back(s[i+offset]);
                }
            }
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/sunao2002002/article/details/52747205