Leetcode6.Zigzag_Conversion

从左到右将字符放在正确的行上,在到达第一行、最后一行时转换方向。
时间复杂度:O(N)
C++代码:

class Solution {
public:
    string convert(string s, int numRows) {

        if (numRows == 1) return s;

        vector<string> rows(min(numRows, int(s.size())));
        int curRow = 0;
        bool goingDown = false;
        for (char c : s) {
            rows[curRow] += c;
            if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
            curRow += goingDown ? 1 : -1;
        }
        string result;
        for (string row : rows) result += row;
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_42263831/article/details/82735208