알고리즘

[python/leetcode] 344번 Reverse String 문제 풀이

grin-quokka 2023. 3. 2. 18:05

https://leetcode.com/problems/reverse-string/description/

 

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

 

요약 : 리턴 없이, 리스트에 있는 문자열을 뒤집어라

 

기본 로직은 다음과 같다.

  1. 리스트를 앞에서 절반까지 돈다
  2. 해당 인덱스의 값과 반대편 값을 swap(교환)한다

 

js라면 구조분해할당으로 swap이 가능하다

[arr[0], arr[1]] = [arr[1], arr[0]]

 

파이썬은 대놓고(?) swap을 할 수 있다.

arr[0], arr[1] = arr[1], arr[0]

 

따라서 아래와 같은 코드로 문제를 풀 수 있다.

def reverseString(s) -> None:
    """
    Do not return anything, modify s in-place instead.
    """
    for i in range(len(s) // 2):
        s[i], s[-(i + 1)] = s[-(i + 1)], s[i]

reverseString(["h", "e", "l", "l", "o"])
# ["o","l","l","e","h"]

 

보완한다면…

  1. 투 포인터 방식으로 풀 수 도 있을 것이다…
  2. 리스트의 reverse 메서드를 쓰면 원본이 바뀌기 때문에 한 줄로 끝낼 수 있다
s.reverse()