leetcode #6 ZigZag Conversion

2017-07-05  本文已影响0人  huntriver

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".

理解了题目意思就非常简单了,我们只需要模拟锯齿的过程就可以了。

/**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
var convert = function (s, numRows) {
    let i = 0;
    let rows = new Array(numRows); //为每一行建立一个字符串
    rows.fill("");

    while (i < s.length) {
        for (let r = 0; r < numRows && i < s.length; r++) { //第一列 从上到下
            rows[r] += s[i++];
        }
        for (let r = numRows - 2; i < s.length && r >= 1; r--) { //第二列 从下到上
            rows[r] += s[i++];
        }
    }
    return rows.join(""); //将所有行连起来
};
上一篇下一篇

猜你喜欢

热点阅读