Skip to content

Latest commit

 

History

History
41 lines (36 loc) · 1.19 KB

0006. Zigzag Conversion.md

File metadata and controls

41 lines (36 loc) · 1.19 KB

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

Screen Shot 2021-11-09 at 21 29 52

Screen Shot 2021-11-09 at 21 30 09

/**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
var convert = function(s, numRows) {
    let res = [];
    let row = 0;
    let up = false;
    
    for(let i = 0; i < s.length; i++) {
        res[row] = (res[row] || "") + s[i];
        if(up) {
            row--;
            if(row === 0) up = false;
        } else {
            row++;
            if(row === numRows - 1) up = true;
        }
    }
        return res.join('')
};