6. N 字形变换

建立一个二维数组,将字符依次放入,最后遍历数组读出即可。
注意,要提前排除边界条件

if (numRows == 1 || s.length() <= numRows) return s;
class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows == 1 || s.size() <= numRows) return s;
        string ans = "";
        int n = s.size();
        vector<vector<string>> map(numRows, vector<string>(n));
        int i = 0, j = 0, t = 0;
        bool changeRow = false;
        while (i < numRows && j < n && t < n) {
            map[i][j] = s[t++];
            if (i == numRows - 1 || changeRow) {
                changeRow = true;
                --i;
                if (i == 0) changeRow = false;
                ++j;
            } else {
                ++i;
            }
        }
        for (int i = 0; i < numRows; ++i) {
            for (int j = 0; j < n; ++j) {
                if (map[i][j] != " ") ans += map[i][j];
                if (ans.size() == n) break;
            }
            if (ans.size() == n) break;
        }
        return ans;
    }
};

你可能感兴趣的:(LeetCode,java,算法,数据结构)