LeetCode : 6 - javascript

LeetCode : 6 - javascript

https://leetcode.com/problems/zigzag-conversion/

6. Zigzag Conversion

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); Example 1: Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2: Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I Example 3: Input: s = "A", numRows = 1 Output: "A" Constraints: 1 <= s.length <= 1000

s consists of English letters (lower-case and upper-case), ',' and '.'.

consists of English letters (lower-case and upper-case), ',' and '.'. 1 <= numRows <= 1000

풀이

주어진 문자열을 지그재그 형태로 배열하고 이를 다시 첫 row부터 순서대로 출력하는 문제이다.

따라서 주어진 numRows의 1차원 배열을 가진 2차원 배열을 만들고 이를 층으로 생각했다.

중요한 것은 문자열의 i번째 문자를 몇 번째 배열에 넣는가 이다.

numRows가 1증가하면 2개의 문자가 추가로 위에 배치되므로 이를 토대로 새로운 인덱스를

let index = i % (2 * numRows - 2)

2 * (numRows - 1) - index 로 만들어줬다.

그리고 index에 맞춰서 배열에 넣으면 지그재그 순서로 들어간다.

var convert = function (s, numRows) { if (numRows === 1) return s; let answer = []; for (let i = 0; i < numRows; i++) { answer.push([]); } s = s.split(""); s.forEach((x, i) => { let index = i % (2 * numRows - 2); if (index >= numRows) index = 2 * (numRows - 1) - index; answer[index].push(x); }); answer = answer.map((x) => x.join("")); return answer.join(""); };

from http://developerlee.tistory.com/59 by ccl(A) rewrite - 2021-12-23 07:02:34