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".

S: 寻找规律建模

将竖列分为一组,斜列分为一组,固定的一行第i个数和第i-1个数index相差2*numRows-2.

    string convert(string s, int numRows) {
        if(numRows < 2) return s;
        int size = s.size(), n = numRows, step = 2*numRows -2;
        string zigs = "";
        for(int i = 0; i < size; i += step) zigs += s[i];
        for(int i = 1; i < n-1;++i){
            for(int idx1 = i, idx2 = step-i;idx1 < size ;idx1+= step, idx2+= step){
                zigs += s[idx1];
                if(idx2 < size) zigs += s[idx2];
            }
        }
        for(int i = n-1; i < size; i += step) zigs += s[i];
        return zigs;
    }

results matching ""

    No results matching ""