LeetCode OJ - ZigZag Conversion

来源:互联网 发布:js 给input class赋值 编辑:程序博客网 时间:2024/06/01 08:11

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

分析:对于同一行,会相距space1或者space2,根据space1和space2迭代求出每一行结果。


伪代码:

for(i = 0; i < N; i++) {    id = i;    space1 = 2(N - i - 1);    space2 = 2 * i;    if(space1 == 0 || space2 == 0) {  //第一行和最后一行加space        space = space1 + space2;        while(id < s.size()) {            ret += s[id];            id += space;        }    } else {                          //中间行先加space1、再加space2        while(id < s.size()) {            ret += s[id];            id += space1;            if(id >= s.size()) break;            ret += s[id];            id += space2;        }    }}return ret;

当然这里的space1和space2的选取也可以用 奇偶列来判断,设置标记为flag = 0 为边界(第0列),flag根据每一次列的计算就加1,根据flag & 0x01来判断是不是中间列:

flag = 0;while(expr) {    if(flag & 0x01) { //中间列    } else {          //非中间列    }    flag++;}


0 0
原创粉丝点击