Share my c++ 14-lines Solution in 18ms


  • 0
    H
    class Solution {
    public:
        string convert(string s, int numRows) {
            string res(s);
            //when rows=1,should coping up correctly
            if(numRows<2)
                return s;
            int div=2*numRows-2,i=0,sz=s.size();
            for(int j=0;j<sz;j+=div)
                res[i++]=s[j];
            for(int t=1;t<numRows-1;t++) {
                int tb=div-2*t;
                for(int j=t;j<sz;j+=div) {
                    res[i++]=s[j];
                    if(j+tb<sz) //notice
                        res[i++]=s[j+tb];
                }
            }
            for(int j=numRows-1; j<sz;j+=div)
                res[i++]=s[j];
            return res;
        }
    }
    

Log in to reply
 

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