12ms C++ solution, easy to understand.


  • 5
    M
    string convert(string s, int numRows) {
        std::string ans(s.size(),'0');
        char* p = &ans[0];
        int part_len = 2*numRows - 2;
        if(numRows == 1 || s.size() == 0) return s;
        for(int i=0; i<numRows; ++i)
        {
            if(i == 0 || i == numRows -1)
                for(int j=i; j<s.size(); j+= part_len) *(p++) = s[j];
            else
            {
                int offset = 2 * i;
                for(int j=i; j<s.size(); offset=part_len-offset,j+= offset) *(p++) = s[j];
            }
        }
        return ans;
    }

Log in to reply
 

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