Diary, Data, IT

[LeetCode] 344. Reverse String - Python 본문

Coding Test/LeetCode

[LeetCode] 344. Reverse String - Python

라딘 2023. 4. 11. 12:07

 

[LeetCode] 344. Reverse String - Python

 

 

Reverse String - LeetCode

Can you solve this real interview question? Reverse String - Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place [https://en.wikipedia.org/wiki/In-place_algo

leetcode.com

 

 

문제

주어진 문자열을 반전시키는 함수를 작성해주세요. 입력 문자열은 배열 형태로 제공됩니다.

O(1)의 메모리를 사용해야 합니다.

 

 

아이디어

O(1)의 메모리만 사용해야하기 때문에 슬라이싱 등을 사용할 수 없다. 

reverse 함수를 사용하거나, 투 포인터를 이용하여 위치를 하나씩 바꿔주는 과정을 거쳐야 한다.

구체적으로 투 포인터를 이용한 방법은, 좌측 포인터와 우측 포인터가 가운데로 한칸씩 이동하며 

포인터가 위치한 자리의 값을 서로 바꿔주는 방식으로 진행한다.

 

 

코드

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

 

코드 2

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        #투 포인터를 이용한 방법
        left = 0; right = len(s) -1

        while left < right:
            s[left], s[right] = s[right], s[left]
            left += 1; right -= 1