C++ solution, simple and easy understand


  • 0
    M
    class Solution {
    public:
        string convert(string s, int numRows) {
            if(numRows == 1)
            return s;
            string result[numRows];
            int i = 0, gap = numRows - 2;
            while(i < s.size())
            {
                for(int j = 0; i < s.size() && j < numRows; j++)
                result[j] += s[i++];
                for(int j = gap; i < s.size() && j > 0; j--)
                result[j] += s[i++];
            }
            string res = "";
            for(int k = 0; k < numRows; k++)
            res += result[k];
            return res;
        }
    };

Log in to reply
 

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