6. ZigZag Conversion

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 s, int numRows);
Example 1:

nput: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"

Explanation:

P I N
A L S I G
Y A H R
P I

AC代码

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

总结

这题蛮简单的,但我的时间复杂度O(n)只超过了30%多的题解,空间复杂度倒是很低

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容