efficient javascript solution


  • 0
    S
    /**
     * @param {string} s
     * @param {number} numRows
     * @return {string}
     */
    var convert = function(s, numRows) {
        // create an numRows array's one for each row, parse the string and keep adding the next char to the next row once you reach the last row start going up till you reach row 0 and now start going down again
        var result = [], row=0, down,zigzag="";
        var len = s.length;
        // Corner Case (Only one row)
    	if (numRows == 1)
    	{
    		zigzag = s;	 
    	} else {
            down=true;
            for(var j=0; j<numRows; j++) {
                result[j]="";
           }
            for(var i=0;i<len; i++){
                result[row]+=s.charAt(i);
                // If last row is reached, change direction to 'up'
                if (row == numRows-1){
                    down = false;
                } else if (row === 0){ // If 1st row is reached, change direction to 'down'
                     down = true;
                }
              (down)? (row++): (row--);
            }
           for(var k=0; k<numRows; k++) {
               zigzag += result[k];
           }
        }
        
        return zigzag;
    };
    

Log in to reply
 

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