Intuitive c++ solution


  • 0
    X

    Please see comments inline for explanation.

    class Solution {
    public:
        string convert(string s, int n) {
            if (n <= 1)     return s;
    
            string result;
            int period = 2 * n - 2;
    
            // row by row
            for (int i = 0; i < n; i++) {
                // column by column
                // column i: i, 2n-2-i, 2n-2+i, 4n-4-i, ...
                int j = i, inc = period - 2 * i;
                while (j < s.size()) {
                    result.push_back(s[j]);
                    // special case: line 0 and n - 1
                    j += (i > 0 && i < n - 1) ? inc : period;
                    inc = period - inc;
                }
            }
    
            return result;
        }
    };

Log in to reply
 

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