Solution for Zigzag conversion in C++


  • 0
    A
    class Solution {
    public:
            string convert(string s, int numRows) {
            
            vector<string> vs(numRows);
            int i = 0;
            
            while (i < s.size()) {
                // Extract the chars in the vertical line of the zigzag (zig)  (going down)
                for (int j = 0; (j < vs.size()) && (i < s.size()); ++j, ++i)
                    vs[j].append(1, s[i]);
                
                // Extract the chars in the diagonal line of the zigzag (zag) (going up/right)
                for (int j = vs.size()-2; (j > 0) && (i < s.size()); --j, ++i)
                    vs[j].append(1, s[i]);
            }
            
            string result;
            for (const string& str : vs)
                result.append(str);
            
            return result;
        }
    };
    

Log in to reply
 

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