[leetcode 6] ZigZag Conversion

来源:互联网 发布:网络教育作业答案 编辑:程序博客网 时间:2024/06/03 14:16

Question:

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


分析:

上图例子中下标顺序为:

0
4
8
121357911132
6
10


可以看出一个规律就是第0行和第nRows-1行的下标间隔是一样的,为interval = 2*nRows-2;中间行的下标是跳跃的,依次为 interval - 2*i;2*i;interval - 2*i;2*i。。。

所以返回的字符串为nRows个字符串串联的结果;


代码如下:

class Solution {public:    string convert(string s, int numRows) {        string result = "";        int interval = 2 * numRows - 2;        int len = s.size();        if(len <= numRows || numRows == 1)            return s;        for(int i = 0; i < numRows; ++i){            int pos = i;            if(i == 0 || i == numRows-1){                while(pos < len){                    result += s[pos];                    pos += interval;                }            }            else{                int b = 2 * i;                while(pos < len){                        result += s[pos];                        b = interval - b;                        pos += b;                }            }        }        return result;    }};


0 0