반응형
오늘은 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('');
};
반응형
'Javascript > 코딩테스트-연습' 카테고리의 다른 글
[JavaScript] 영어가 싫어요 - 프로그래머스 (27) | 2024.03.20 |
---|---|
[JavaScript] 옷 가게 할인받기 - 프로그래머스 (22) | 2024.03.20 |
[JavaScript] 최빈값 구하기 - 프로그래머스 (23) | 2024.03.18 |
[JavaScript] 평행 - 프로그래머스 (27) | 2024.03.14 |
[JavaScript] 점의 위치 구하기 (32) | 2024.02.27 |