본문 바로가기
LeetCode

[LeetCode] 6. Zigzag Conversion

by JungSeung 2023. 10. 13.
728x90

https://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: "PAYPALISHIRING"

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

 

Code :

var convert = function(s, numRows) {
    // 특수한 경우 처리: 변환할 필요 없는 경우
    if (s.length <= numRows || numRows < 2) {
        return s;
    }
    const len = s.length;
    const num = 2 * (numRows - 1);
    // 각 행에 해당하는 문자열을 저장할 배열 초기화
    let res = Array(numRows).fill('');
    let tmp = 0;
    // 문자열을 순회하면서 각 행에 문자 추가
    for (let i = 0; i < len; i++) {
        tmp = i % num;
        // Z 모양의 꼭대기 부분에 해당하는 행에 추가
        if (tmp < numRows) {
            res[tmp] += s[i];
        }
        // Z 모양의 내부 부분에 해당하는 행에 추가
        else {
            res[num - tmp] += s[i];
        }
    }
    // 각 행의 문자열을 이어붙여 최종 결과 생성
    return res.join('');
};

 

Solutions Code :

var convert = function(s, numRows) {
    // 행이 1인 경우에는 변환할 필요가 없으므로 주어진 문자열 그대로 반환
    if (numRows === 1) {
        return s;
    }
    // 결과 문자열을 저장할 변수 초기화
    let result = '';
    // 입력 문자열의 길이
    const n = s.length;
    // 주기의 길이 (한 번의 Z 패턴 주기의 길이)
    const cycleLen = 2 * numRows - 2;
    // 행을 기준으로 Z 패턴을 구성
    for (let i = 0; i < numRows; i++) {
        for (let j = 0; j + i < n; j += cycleLen) {
            // 현재 행에 속하는 문자를 결과에 추가
            result += s[j + i];
            // 첫 번째 행과 마지막 행이 아니며, 대각선에 해당하는 문자를 추가
            if (i !== 0 && i !== numRows - 1 && j + cycleLen - i < n) {
                result += s[j + cycleLen - i];
            }
        }
    }
    // 최종적으로 변환된 결과 문자열 반환
    return result;
};

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90