o(n) solution for ZigZag Conversion


  • -1
    A
    string convert(string s, int numRows) {
            vector<vector<char> > mat(numRows);
            int dir = 1;
            int curr_row = 0;
            for (int i = 0;i < s.size();i++){
                mat[curr_row].push_back(s[i]);
                if (dir == 1) {
                    if (curr_row == numRows - 1) {
                        dir = -1;
                    }
                }
                else {
                    if (curr_row == 0) {
                        dir = 1;
                    }
                }
                curr_row += dir;
                if (curr_row < 0 || curr_row >= numRows) {
                    curr_row = 0;
                }
            }
            string ans = "";
            for (int i = 0;i < numRows;i++){
                for (int j = 0;j < mat[i].size();j++) {
                    ans += mat[i][j];
                }
            }
            return ans;
        }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.