문제주소 : https://leetcode.com/problems/zigzag-conversion/
ZigZag Conversion - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
<문제 설명>
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 '.'.
 - 1 <= numRows <= 1000
 
<풀이법>
▒ 한줄 개념: 인덱스 계산 ▒
얼핏보면 복잡해보이지만 단순 인덱스 계산 문제입니다.
Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" 을 예로 들어보겠습니다. 아래와 같은 결과가 나와야합니다.

결과를 2차원 배열로 적어보면, 다음과 같습니다.
[
[P, A, H, N],
[A, P, L, S, I, I, G],
[Y, I, R]
]
위 배열을 groups 라고 했을 때, PAYPALISHIRING은 groups 배열에 아래와 같이 삽입됩니다.
P -> groups[0]에 삽입
A -> groups[1]에 삽입
Y -> groups[2]에 삽입
P -> groups[1]에 삽입
A -> groups[0]에 삽입
L -> groups[1]에 삽입
I -> groups[2]에 삽입
S -> groups[1]에 삽입
H -> groups[0]에 삽입
...
이렇게 보면 규칙이 쉽게 보입니다. groups에 삽입하게 될 인덱스 값이 0, 1, 2, 1, 0, 1, 2 ... 의 식으로 numRows 값을 기준으로 작아졌다 커졌다를 반복하는 것입니다.
위처럼 2차원 배열로 만들어주고, 순서대로 join하여 주면 정답이 쉽게 완성됩니다.
<코드(Javascript)>
/**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
var convert = function(s, numRows) {
    let count = 0;
    let countUp = true;
    const groups = [];
    for(let i = 0; i < numRows; i++){
        groups.push([]);
    }
    s.split('').map(char => {
        groups[count].push(char);
        if(countUp){
            count++;
            if(count === numRows){
                count = numRows < 2 ? 0 : count-2;
                countUp = !countUp;
            }
        }else{
            count--;
            if(count === -1){
                count = numRows < 2 ? 0 : count+2;
                countUp = !countUp;
            }
        }
    })
    return groups.reduce((acc, cur) => {
        return acc + cur.join('');
    }, '');
};
더 많은 코드 보기(GitHub) : github.com/dwkim-97/CodingTest
'LeetCode' 카테고리의 다른 글
| [리트코드] 1130. Minimum Cost Tree From Leaf Values / Javascript (0) | 2021.09.08 | 
|---|---|
| [리트코드] 1647. Minimum Deletions to Make Character Frequencies Unique / Javascript (0) | 2021.09.08 | 
| [리트코드] 142. Linked List Cycle II / Javascript (0) | 2021.06.08 | 
| [리트코드] 141. Linked List Cycle / Javascript (0) | 2021.06.08 | 
| [리트코드] 139. Word Break / Javascript (0) | 2021.06.07 |