LeetCode/Top Interview 150

6. Zigzag Conversion

hyunkookim 2024. 11. 28. 15:32

6. Zigzag Conversion

 

https://youtu.be/Q2Tw6gcVEwc?si=uqM3oulxloxx3h1P

 

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        # numRows가 1인 경우 변환할 필요가 없으므로 입력 문자열 그대로 반환
        if numRows == 1: 
            return s

        res = ""  # 변환된 결과 문자열을 저장할 변수

        # 각 행(row)을 순회하며 변환된 문자열을 생성
        for r in range(numRows):
            increment = 2 * (numRows - 1)  # 각 주기에서의 문자 간격 (ZigZag 주기)

            # 현재 행에서의 모든 문자를 순회
            for i in range(r, len(s), increment):
                res += s[i]  # 주기적으로 문자를 추가
                
                # 대각선 문자를 추가하는 조건:
                # - 현재 행이 첫 번째(r==0) 또는 마지막 행(r==numRows - 1)이 아님
                # - 대각선 문자(i + increment - 2 * r)가 유효한 인덱스 범위(< len(s))에 있음
                if r > 0 and r < numRows - 1 and i + increment - 2 * r < len(s):
                    res += s[i + increment - 2 * r]  # 대각선 문자 추가

        # 최종 변환된 결과 반환
        return res

'LeetCode > Top Interview 150' 카테고리의 다른 글

68. Text Justification  (0) 2024.11.28
28. Find the Index of the First Occurrence in a String  (0) 2024.11.28
12. Integer to Roman  (0) 2024.11.28
42. Trapping Rain Water  (0) 2024.11.28
14. Longest Common Prefix  (2) 2024.11.27