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)

  1. P A H N
  2. A P L S I I G
  3. 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:

  1. string convert(string s, int numRows);

Example

  1. Input: s = "PAYPALISHIRING", numRows = 3
  2. Output: "PAHNAPLSIIGYIR"
  1. Input: s = "PAYPALISHIRING", numRows = 4
  2. Output: "PINALSIGYAHRPI"
  3. Explanation:
  4. P I N
  5. A L S I G
  6. Y A H R
  7. P I
  1. Input: s = "A", numRows = 1
  2. Output: "A"

Solution

使用一个二维数组,存储每行结果。

  1. var convert = function (s, numRows) {
  2. if (numRows === 1) return s;
  3. const conversionArr = [];
  4. for (let i = 0; i < numRows; i++) {
  5. conversionArr.push([]);
  6. }
  7. for (let i = 0; i < s.length; i++) {
  8. const quotient = parseInt(i / (numRows - 1));
  9. const remainder = i % (numRows - 1);
  10. if (quotient % 2 !== 0) {
  11. conversionArr[numRows - remainder - 1].push(s[i]);
  12. } else {
  13. conversionArr[remainder].push(s[i]);
  14. }
  15. }
  16. let res = "";
  17. for (let i = 0; i < conversionArr.length; i++) {
  18. for (let ii = 0; ii < conversionArr[i].length; ii++) {
  19. res += conversionArr[i][ii];
  20. }
  21. }
  22. return res;
  23. };



另一种方式

var convert = function (s, numRows) {
    if (numRows === 1) return s;

    const rows = [];
    for (let i = 0; i < numRows; i++) {
        rows.push("");
    }

    var curRow = 0;
    var goingDown = false;
    for (let i = 0; i < s.length; i++) {
        rows[curRow] += s[i];

        if (curRow === 0 || curRow === numRows - 1) goingDown = !goingDown;

        curRow += goingDown ? 1 : -1;
    }

    let res = "";
    for (let i = 0; i < rows.length; i++) {
        res += rows[i];
    }

    return res;
};