LeetCode 6. Z 字形变换

Posted by cody1991 on August 2, 2020

简单思路:按照题目意思画出对应的运行流程,就可以看出规律,写出对应的代码了

6. Z 字形变换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
var convert = function (s, numRows) {
  if (numRows === 1) return s;
  const arr = Array(numRows).fill("");

  let index = 0;
  let up = true;
  for (let i = 0; i < s.length; i++) {
    const cur = s[i];

    arr[index] += cur;

    if (up && index === numRows - 1) {
      up = false;
      index--;
    } else if (!up && index === 0) {
      up = true;
      index++;
    } else if (up) {
      index++;
    } else {
      index--;
    }
  }

  return arr.join("");
};
const s = "AB",
  numRows = 1;

console.log(convert(s, numRows));