본문 바로가기

알고리즘 스터디

[Leetcode/파이썬] 6. Zigzag Conversion

반응형

Zigzag Conversion

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

 

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

 

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if numRows == 1 or len(s) == 1 :
            return s

        idx = 0
        d = 1

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

        for j in range(len(s)) :
            if idx == 0 :
                d = 1

            elif idx == numRows - 1 :
                d = -1

            word_stack[idx].append(s[j])
            idx += d

        res = []
        for word in word_stack :
            res += word

        return "".join(res)

처음에는 좀 헤맸다. 

  • 지그재그 형태를 어떻게 구현할까. 

이 부분은 참고를 하였다. idx가 처음이면 +1로, numRows이면 -1로 바꿔서 계속해서 더해준다. 코드를 보면 비교적 쉽게 해결할 수 있다. 

처음 가지치기를 안해서 오답을 제출했다. 

반응형