Super short and simple single level loop C++ solution


  • 1
    S

    The idea is to generate sequence of 0 1 2 1 0 1 2 1 0 to put the next character in the right bucket and then join them together at the end.
    The trick is to generate j = 0 1 2 1 0 1 2 ... sequence from i = 0 1 2 3 4 5 6 ... by j = n-1-abs(i%(n*2-2)-n+1)
    Plot
    See here

    string convert(string s, int numRows) {
        if (numRows == 1) return s;
        vector<string> bucket(numRows);
        for (int i = 0; i < s.size(); ++i) {
            int j = numRows-1-abs(i%(numRows*2-2)-numRows+1); 
            bucket[j] += s[i];
        }
        string ans;
        for (string b: bucket) {
            ans += b;
        }
        return ans;
    }
    

Log in to reply
 

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