Easy to understand c++ solution


  • 0
    C

    When scanning on linei (i = 0, 1, 2, ..., numRows - 1)
    - i == 0 or i == numRows - 1, step == 2*numRows - 2
    - 0 < i < numRows - 1, there are tow steps in a 2*numRows - 2, l1 == step - 2*il2 == 2*i

    string convert(string s, int numRows) {
        int sl = s.length();
        if(numRows<2 || sl < 3 || sl <= numRows) return s;
        
        string res = "";
        
        // i == 0
        int i = 0;
        while(i < sl)
        {
            res += s.at(i);
            i += 2*numRows - 2;
        }
        
        // 0 < i < numRows - 1
        for(i = 1; i < numRows - 1; i ++)
        {
            int step1 = 2*numRows - 2 - 2*i;
            int step2 = 2*i;
            
            int index = i;
            res += s.at(index);
            index += step1;
            
            while(index < sl)
            {
                res += s.at(index);
                index += step2;
                if(index < sl)
                {
                    res += s.at(index);
                    index += step1;
                }
            }
        }
        
        // i == numRows - 1
        i = numRows - 1;
        while(i < sl)
        {
            res += s.at(i);
            i += 2*numRows - 2;
        }
        
        return res;
    }
    

Log in to reply
 

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