Simple C++ solution (based on regularly changing increment)


  • 0
    B

    Reference: thanks for twntwn3838's derivation. It helped me correct mistake in my codes.

    class Solution {
    public:
        string convert(string s, int numRows) {
            string ans;
            int n = s.length();
            if(numRows == 1) return s;
    
            for(int i = 0; i < numRows; i++){
                int j = i;
                int r = 2 * i;
                int l = 2 * (numRows - 1);
                while(j < n){
                    ans += s[j];
                    if(i == 0 || i ==(numRows - 1)){ // - First and last row.
                        j += l;
                    }
                    else{ //Alternatively change the increment. - Other rows.
                        r = l - r;
                        j += r;
                    }
                }
            }
            return ans;
        }
    };
    

Log in to reply
 

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