넘치게 채우기

[LeetCode] 6. Zigzag Conversion 본문

PS/LeetCode

[LeetCode] 6. Zigzag Conversion

riveroverflow 2023. 8. 5. 14:22
728x90
반응형

https://leetcode.com/problems/zigzag-conversion/description/?envType=study-plan-v2&envId=top-interview-150 

 

Zigzag Conversion - LeetCode

Can you solve this real interview question? Zigzag Conversion - 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

leetcode.com

문제 유형 : 문자열 처리 / 배열

문제 난이도 : Medium

 

문제

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);

주어진 문자열 s를 지그재그 모양으로 재배열한 뒤, 그것을 가로순으로 읽어서 반환하시오.

 

풀이

numRows개만큼의 문자열 배열을 선언합니다.

그 뒤, 배열의 각 문자열에 지그재그 순으로 문자열 s의 글자를 삽입합니다.

문자를 삽입하고나서, 행을 바꿔주고(처음에는 내려감), 행이 범위를 벗어나면 방향을 바꿔줍니다.

지그재그로 문자열을 나누는 작업이 끝나면, 배열의 문자열들을 순서대로 합쳐줍니다.

 

 

코드(C++)

class Solution {
public:
    string convert(string s, int numRows) {
        ios_base::sync_with_stdio(false);
        cin.tie(nullptr);

        if(numRows == 1) return s; // numRows가 한줄이면 지그재그의 의미가 없다.

        vector<string> table (numRows);
        const int n = s.size();

        int row = 0;
        bool isGoingDown = true;
        for(int i = 0; i < n; i++){
            table[row].push_back(s[i]);

            if(isGoingDown){
                row++;
                if(row >= numRows){
                    isGoingDown = !isGoingDown;
                    row -= 2;
                }
            }
            else{
                row--;
                if(row < 0){
                    isGoingDown = !isGoingDown;
                    row += 2;
                }
            }
        }

        string converted = "";
        for(auto str : table){
            converted += str;
        }

         return converted;
    }
};
728x90
반응형