C++ Solution, using extra space


  • 0
    W
    string convert(string s, int numRows) {
        if(numRows == 1 || s == "") {
            return s;
        }
    
        vector<string> temp(numRows, "");
        vector<int> rows(2*numRows - 2);
        for (int i = 0; i < numRows; i++) {
            rows[i] = i;
        }
        for(int i = 0; i < numRows - 2; i++) {
            rows[rows.size() - 1 - i] = i + 1; 
        }
        
        for (int i = 0; i < s.size(); i++) {
            temp[rows[i%rows.size()]] += s[i];
        }
        
        string ans = "";
        for(int i = 0; i < numRows; i ++) {
            ans += temp[i];
        }
        
        return ans;
    }

Log in to reply
 

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