Share my C++ code for ZigZag


  • 0
    C

    string Convert(string s, int nRows) {
    int N, n1, n2, in = 2;
    if ((N = s.length()) <= nRows || nRows <= 1)
    return s;
    string pt;
    // lines
    int k = 0;
    int base = in*nRows - in; // loop base;
    n1 = base;
    n2 = 0; // step increments
    while (k!=nRows&&n1>=0&&n2>=0){
    pt.push_back(s[k]); // the line first-one;
    int ic = k;
    while(1){
    if (k != nRows - 1) // not for the last row;
    {
    if (ic + n1 >= N)
    break;
    ic += n1;
    pt.push_back(s[ic]);
    }
    if (k != 0) // not for the first row;
    {
    if (ic + n2 >= N)
    break;
    ic += n2;
    pt.push_back(s[ic]);
    }
    }
    n1 -= in;
    n2 += in;
    k++;
    }
    return pt;
    }


Log in to reply
 

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