LeetCode 344. Reverse String

개발공부를해보자·2025년 1월 4일

LeetCode

목록 보기
2/95

파이썬 알고리즘 인터뷰 문제 2번(리트코드 344번) Reverse String
https://leetcode.com/problems/reverse-string/

주어진 리스트를 in-place로 뒤집는 문제.

나의 풀이

class Solution:
    def reverseString(self, s: List[str]) -> None:
        left, right = 0 , len(s) - 1
        while left < right:
            s[left], s[right] = s[right], s[left]
            left += 1
            right -= 1
        

Two pointers 풀이, 정직한 풀이.

다른 풀이1

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        
        s[:] = s[::-1]

재밌는 점은 s=s[::-1]은 in-place가 아니지만
s[:] = s[::-1]은 in-place가 맞다.
일종의 트릭스러운 풀이

다른 풀이2

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        
        s.reverse()

아! 이 풀이를 보고 든 생각이다. 그래 이렇게 하는게 파이썬스러운 풀이지.

profile
개발 공부하는 30대 비전공자 직장인

0개의 댓글