C++ solution (math based)


  • 0
    T
    class Solution {
    public:
        string convert(string s, int numRows) {
            if(numRows == 1)
                return s;
            int n = s.size();
            string res;
            int d = 2*(numRows-1); //distance between vertical lines
            for(int i=0; i<numRows; i++){
                int start = i;
                while(start < n){
                    res += s[start];
                    if(i!=numRows-1 && i!=0){//if not the first or last row
                        start += (d-2*i); //distance between a slash line and the vertical line before it
                        if(start < n)
                            res += s[start];
                        start += 2*i; //distance between a slash line and the vertical line after it
                    }
                    else
                        start += d;
                }
            }
            return res;
        }
    };
    

Log in to reply
 

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