【Leetcode】6. ZigZag Conversion

1. 题目

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. 思路

按规则计算每行的下标顺序进行打印即可。
首行和末行可以同质对待,但是会有下标重叠,进行一下特殊处理即可。

3. 代码

耗时:16ms

class Solution {
public:
    string convert(string s, int numRows) {
        int len = s.length();
        if (numRows <= 1 || len <= numRows) {
            return s;
        }
        string so;
        so.resize(len);
        so = "";
        int l = numRows * 2 - 2;
        for (int ri = 0; ri < numRows; ri++) {
            int i = 0;
            int last = -1;
            while (true) {
                int base = i * l;
                int p1 = base + ri;
                int p2 = base + l - ri ;
                if (p1 < len && p1 != last) so += s[p1];
                if (p2 < len && p2 != p1) so += s[p2];
                i++;
                last = p2;
                if (p2 >= len) break;
            }
        }
        return so;
    }
};
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000007274692
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞