6. ZigZag Conversion


Problem

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 text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

Solution

ZigZag pattern is like this:

\    /\    /\    /\    /
 \  /  \  /  \  /  \  / 
  \/    \/    \/    \/

Take each corner as reference point, for example:

\     /  4
 \   /   3
  a c    2
   b     1
   reference point

a and c are in the second row, base on the reference point b. We can easily calculate the distance between a and c: row * 2 - 2

Same as below, where the reference point f is on top.

   reference point
   f    1
  / \   2
 e   g  3
/     \ 4

So we just have to keep flipping the reference point.

Only for row 1, every time it flips the reference point becomes itself. So just skip it.

/**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
var convert = function(s, numRows) {
    if (s.length <= 1 || numRows === 1) { return s }
    var result = ''
    for (let n = 0; n < numRows; n += 1) {
        let row = numRows - n
        for (let i = n; i < s.length; ) {
            // row 1 flips to itself
            if (row !== 1) {
                result += s[i]
                i += row * 2 - 2
            }
            // flip the reference point
            row = numRows + 1 - row
        }
    }
    return result
};

results matching ""

    No results matching ""