Skip to content

Latest commit

 

History

History
64 lines (46 loc) · 1.8 KB

6. Zigzag Conversion[Medium].md

File metadata and controls

64 lines (46 loc) · 1.8 KB

6. Zigzag Conversion[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:
            lst = (list(range(numRows)) + list(range(numRows - 2, 0, -1))) * int(len(s) / numRows + 1)
            answer = [""] * numRows
            idx = 0
            for i in lst:
                if idx < len(s):
                    answer[i] += s[idx]
                    idx += 1
            answer = "".join(answer)
            return answer

    numRows에 따라, 0 1 2 1 0 1 2 1 0 이렇게 진행되므로, 미리 lst 변수에 숫자를 만들어서 넣어주었다. 별로 좋지 않은 풀이다...

    여튼 이렇게 해서, answer[0], answer[1] .. 에 각각 지그재그 문자를 넣어주고, 나중에 answer을 다 합쳐주는 풀이다.