[Leetcode] 6. Zigzag Conversion
[Leetcode] 6. Zigzag Conversion

[Leetcode] 6. Zigzag Conversion

카테고리
📚 Algorithm
작성자
박용성박용성
작성일
2024년 06월 14일
태그
Python
Leetcode
Slug
Leetcode-6
floatFirstTOC: right

🖥️ 시작하며

문자를 지그재그로 출력하는 되는 문제입니다.
 
  1. 각각의 문자열을 저장할 문자를 생성합니다.
    1. res = ["" for _ in range(numRows)]
  1. 처음 방향을 정한 후, numRows 만큼 왔다가 되돌아가는 방식으로 배열에 저장합니다.
    1. res = ["" for _ in range(numRows)] index = 0 direction = 1 for c in s: res[index] += c if index == 0: direction = 1 elif index == numRows - 1: direction = -1 index += direction
 

⚙️ Python

from typing import List class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s res = ["" for _ in range(numRows)] index = 0 direction = 1 for c in s: res[index] += c if index == 0: direction = 1 elif index == numRows - 1: direction = -1 index += direction return "".join(res) if __name__ == "__main__": sol = Solution() print(sol.convert("PAYPALISHIRING", 3)) print(sol.convert("PAYPALISHIRING", 4)) print(sol.convert("A", 1))
 

📌 소감

 

댓글

guest