Easy to understand C++ code


  • 0
    C
    class Solution {
    public:
        string convert(string s, int numRows) {
            int n = numRows, len = int(s.length());
            if (n == 1) return s;
            string newStr = "";
            for (int i = 1; i < n + 1; i++) {
                int step1 = 2*(n - i); 
                int start = i - 1;
                if (i == 1)
                    for (start; start < len; start += step1)
                        newStr += s[start];
                else if (i == n) {
                    step1 = 2*n - 2;
                    for (start; start < len; start += step1)
                        newStr += s[start];
                }
                else {
                    int step2 = 2*(n - 1) - step1;
                    for (start; start < len; start += step2) {
                        newStr += s[start];
                        swap(step1, step2);
                    }
                }
            }
            return newStr;
        }
    };
    

Log in to reply
 

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