[Python 으로 푸는 Leetcode]6. ZigZag Conversion

느린 개발자·2020년 12월 14일
1

Coding Test

목록 보기
5/21

📌Problem

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

leetcode 에서 풀기


📝Solution

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        index_dict = dict()
        zigzag_index = 0
        down = 1  # Down flag
        up = -1  # Up flag
        move = 0
        for character in s:
            if zigzag_index == 0:  # Down
                move = down
            elif zigzag_index == numRows - 1:  # Up
                move = up

            index_dict[zigzag_index] = index_dict.get(zigzag_index, '') + character
            zigzag_index +=move  # Move index

        return ''.join(index_dict.values())
  • Time complexity : O(N)O(N)

  • numRows=4

    PAYPALISHIRING
    01232101232101

    같은 인덱스(=같은 행)를 가진 문자끼리 문자열을 만들어서 오름차순 인덱스(행이 증가하도록)로 문자열 concat

profile
남들보단 느리지만, 끝을 향해

0개의 댓글