Simple and fast C++ 18ms solution, best for beginner


  • 0
    B
    string convert(string s, int numRows) {
    if ( s.empty() || numRows < 2 )
    {
        return s;
    }
    string ans = "";
    int len = s.length();
    int pos1 = 0;
    int pos2 = 0;
    //take care of top row
    while ( pos1 < len )
    {
        ans += s[ pos1 ];
        pos1 += 2 * numRows - 2;
    }
    //take care of middle row
    for ( int i = 1; i < numRows - 1; i++)
    {
        pos1 = i;
        pos2 = pos1 + 2 * numRows - 2 - 2 * i;
        while ( pos1 < len )
        {
            ans += s[ pos1 ];
            if ( pos1 < pos2 && pos2 < len )
            {
                ans += s[ pos2 ];
            }
            pos1 += 2 * numRows - 2;
            pos2 = pos1 + 2 * numRows - 2 - 2 * i;
        }
    }
    //take care of bottom row
    pos1 = numRows - 1;
    while ( pos1 < len )
    {
        ans += s[ pos1 ];
        pos1 += 2 * numRows - 2;
    }
    return ans;
    }

Log in to reply
 

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