floatFirstTOC: right
🖥️ 시작하며
문자를 지그재그로 출력하는 되는 문제입니다.
- 각각의 문자열을 저장할 문자를 생성합니다.
res = ["" for _ in range(numRows)]
- 처음 방향을 정한 후,
numRows
만큼 왔다가 되돌아가는 방식으로 배열에 저장합니다.
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))
댓글