몰입공간

[Leetcode] 6. Zigzag Conversion (python) 본문

Algorithm/Leetcode

[Leetcode] 6. Zigzag Conversion (python)

sahayana 2023. 9. 24. 19:09

#1.  문제

https://leetcode.com/problems/zigzag-conversion/

 

LeetCode - The World's Leading Online Programming Learning Platform

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

 

문자열 s를 주어진 정수 값 numRows의 row 수로 다음과 같이 지그재그 패턴으로 나타낼 수 있을 때,

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

라인별로 문자열을 재조합하는 문제

Input: 
s = "PAYPALISHIRING"
numRows = 4

Output: "PINALSIGYAHRPI"

Explanation:

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

#2.  풀이

 

 

class Solution:
    def convert(self, s: str, numRows: int) -> str:

        result = ""

        rows = [[] for _ in range(numRows)]

        row = 0

        convert = False

        if numRows == 1:
            return s

        for char in s:

            rows[row].append(char)

            if convert is not True:
                row += 1
            else:
                row -= 1

            if row == numRows - 1:
                convert = True
            elif row == 0:
                convert = False

        for r in rows:
            temp = "".join(r)
            result += temp

        return result

 

numRows 만큼의 빈 리스트를 하나의 리스트안에 생성하고, 주어진 문자열을 앞에서 부터 차례대로 각 리스트에 순서대로 한글자씩 넣어준다.

이때 마지막 row를 만나면 (인덱스이기 때문에 numRows - 1) 이때 문자열을 삽입하는 순서의 전환이 이루어져야 하기 때문에  convert 플래그를 True로 바꿔준다.

다시 처음 row를 만나면 이때 또 전환이 이루어지기 때문에 convert 플래그를 반대로 설정한다.

 

모든 문자열이 삽입됐으면, 각 row는 하나의 line과 같이 때문에 차례대로 문자열을 만들어 이어붙어주면 풀이 완성

 

변곡점 (마지막 row 이후 꺾이는 부분)을 기준으로 어떻게 패턴을 만들 수 있는지 고민을 많이 했던 문제,

규칙을 알아내는데 시간이 좀 많이 걸렸고, convert 플래그를 따로 설정하지 않고 풀다가 애를 많이 먹었다.

Comments