C++ solution


  • 0
    R

    class Solution {
    public:
    string convert(string s, int numRows) {
    //End case check
    if(numRows == 1)
    return s;

        //Get length of string
        int len = s.length();
        
        //Initialize array to store substrings
        string array[numRows];
        
        //Direction of movement
        bool down = true;
        
        //start from first row
        int row = 0;
        
        //Iterate over the string
        for(int i = 0; i < len; i++) {
            //Store value of string in array
            array[row].push_back(s[i]);
            
            //If top is reached then update direction
            if(row == 0)
                down = true;
            
            //If end is reached then update direction
            if(row == numRows - 1)
                down = false;
            
            //Update rows according to direction
            if(down)
                row++;
            else
                row--;
        }
        
        string sol = "";
        
        //Concat strings
        for(int i = 0; i < numRows; i++){
            sol = sol + array[i];
        }
        
        return sol;
        
    }
    

    };


Log in to reply
 

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