본문 바로가기
Javascript/코딩테스트-연습

[JavaScript] ZigZag Conversion - Leetcode

by BeomBe 2024. 3. 19.
반응형

오늘은 Leetcode에 있는 ZigZag Conversion 문제를 풀어봤습니다.

 

자세한 문제설명은 아래 링크를 참조해주세요.

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

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"

 

간단히 이해하자면 아래와 같다.

 

나의 풀이

var convert = function(s, numRows) {
    // 1. 지그재그 시퀀스로 배열을 만듭니다.
    const zigzag = [...new Array(numRows).keys()]; 
    zigzag.push(...zigzag.slice(1, -1).reverse());
    // 2. 필요한 행만큼의 문자열로 배열을 만듭니다.
    const rows = new Array(numRows).fill('');
    // 3. 지그재그 순서로 행 문자열에 문자를 추가합니다.
    [...s].forEach((c, i) => (rows[zigzag[i % zigzag.length]] += c));
    // 4. 배열의 행 문자열을 함께 결합합니다.
    return rows.join('');
};
반응형