[JS] Zigzag Conversion

2022. 10. 26. 14:02

🔒 문제 (LeetCode 6)

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"

 


 

🔑 해결

🌌 알고리즘

P                A                H                  N
    A        P       L      S        I          I         G
         Y                 I                 R

위와 같은 형식으로 배치하는 것이 지그재그 배치이다.

row를 +방향으로 이동하다가  numRows만큼 이동하면 reverse하여 -방향으로 다시 이동하고 첫 row에 도달하면 다시 앞의 과정을 반복하여 문자열을 변환한다.

/**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
var convert = function(s, numRows) {
    const len = s.length;
    if (numRows < 2 || len < numRows) {
        return s;
    }
    
    const rows = new Array(numRows).fill('');
    let reverse = false;
    let count = 0;
    for (let i = 0; i < len; i++) {
        rows[count] += s[i];
        reverse? count--: count++;
        if (count === numRows - 1 || count === 0) {
            reverse = !reverse;
        }
    }
    
    return rows.join('');
};

'코딩테스트 (JS) > ETC' 카테고리의 다른 글

[JS] MinAvgTwoSlice  (0) 2022.10.27
[JS] 가장 큰 수  (0) 2022.10.26
[JS] Maximum Consecutive Floors Without Special Floors  (0) 2022.10.08
[JS] Happy Number  (0) 2022.09.28
[JS] Shuffle an Array  (0) 2022.09.28

+ Recent posts