ZigZag Conversion

来源:互联网 发布:jd是网络用语什么意思 编辑:程序博客网 时间:2024/05/21 10:32

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


一般这样的题目都是需要先找到规律,我找的规律这这样的

每一个完整的列之间的间隔是行数+2(记为Cnt),从第二行开始,间隔呈现出这样的规律,Cnt - 2 * (所在行 - 1)  , 2 * (所在行 - 1) ,然后就是这样的一个循环。


最后的C++代码贴上:

    string convert(string s, int nRows) {        if (s.size() == 0 || 1 == nRows) {            return s;        }        string sRet;        int iCnt = 2 * (nRows - 1);        for (int iRow = 1 ; iRow <= nRows ; ++iRow ) {                int iInc[2] , tmp = 0;                if (iRow == 1 || iRow == nRows) {                    iInc[0] = iCnt;                    iInc[1] = iCnt;                }                else {                    iInc[0] = iCnt - 2 * (iRow - 1);                    iInc[1] = iCnt - iInc[0];                }                for (int j = iRow - 1 ; j  < s.size() ; j += iInc[tmp] , tmp = (++tmp) % 2) {                    sRet += s[j];                }        }        return sRet;    }



0 0