LeetCode OJ : 6 ZigZag Conversion

来源:互联网 发布:c程序员笔试题题库 编辑:程序博客网 时间:2024/05/16 09:52

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

这个例子分为了三行,所以需要三个string对象来保存每一行的字符串,最后按顺序(从第一排到最后一排)将字符串相加起来;这个求和之后的字符串就是所求,将它返回;

把变换之后的看成是一个周期变化的,第一个周期 P-A-Y-P,第二个周期A-L-I-S,第三个周期....

每个周期又有规律可循,P-A-Y分别存放在0-1-2行;接下来的p存放在1行;然后又是下一个周期。。。。


比如是四排的时候;


第一个周期A-B-C-D-E-F;首先将A-B-C-D存放在0-1-2-3排,再将E-F存放在2-1排。。所以存放在不同排的顺序应该是0-1-2-3-2-1;

所以A-B-C-D-E-F对应存放在0-1-2-3-2-1;

每2 * numRows-2个字符依次存放在0-1-2-....-(numRows-1)-(numRows-2)-......--1;

class Solution {public:    string convert(string s, int numRows) {        vector<string> vstr(numRows);        int i = 0, j = 0;                if(s.size() == 0){            return s;        }                for (i = 0; i < s.size(); ){            for (j = 0; j < numRows; ++j){                if(i == s.size()){                    break;                }                vstr[j].push_back(s[i++]);            }                        for (j = numRows-2; j >=1 ; --j){                if(i == s.size()){                    break;                }                vstr[j].push_back(s[i++]);            }                        if(i == s.size()){                string str;                for (i = 0; i < numRows; ++i){                    str += vstr[i];                }                return str;            }        }    }};


运行效率比较低,不过这个运行时间不稳定,第一次提交的时候是22/%。。

0 0