ZigZag Solution-C++


  • 0
    X
    class Solution {
        public:
        string convert(string s, int numRows) {
            if (s.size() == 0 || s.size() == 1 || s.size() <= numRows ||  numRows == 1){
                return s;
            }
        
            vector<vector<char>> zigZag(numRows, vector<char>());
        
            int l = 0;
            int j = 0;
            while (l < s.size()){
                if (j % (numRows - 1) == 0){
                    for (int i = 0; i < numRows && l < s.size(); i++){
                        zigZag[i].push_back(s[l]);
                        l++;
                    }
                }else{
                    zigZag[numRows - j % (numRows - 1) - 1].push_back(s[l]);
                    l++;
                }
                j++;
            }
        
            string output;
            for (int i = 0; i < numRows; i++){
                for (int k = 0; k < zigZag[i].size(); k++){
                    output += zigZag[i][k];
                }
            }
        
            return output;
        }
    };

Log in to reply
 

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