首页 > 其他 > 详细

ZigZag Conversion

时间:2015-01-20 10:27:46      阅读:243      评论:0      收藏:0      [点我收藏+]

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


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

技术分享

每一个完整的列之间的间隔是行数+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;
    }



ZigZag Conversion

原文:http://blog.csdn.net/u012458164/article/details/42913479

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!