본문 바로가기

카테고리 없음

[LeetCode] 344. Reverse String

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

 

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

 

Problem:

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 with O(1) extra memory.

문자열을 뒤집는 함수를 작성하라. 입력값은 문자 배열이며, 리턴 없이 리스트 내부를 직접 조작하라.


Example 1:

Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

 

Constraints:


[풀이 1] 투 포인터를 이용한 스왑

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

2개의 포인터를 이용해 범위를 조정해가며 풀이하는 방식이다. 여기서는 점점 더 범위를 좁혀가며 스왑하는 형태로 풀이할 수 있다.

 

[풀이2] 파이썬다운 방식

class Solution:
    def reverseString(self, s: List[str]) -> None:
        s.reverse()

내가 작성한 코드와 동일하다.

파이썬의 기본 기능을 이용하면 단 한 줄로 쉽게 풀이할 수 있다. 이러한 방식들을 흔히 파이썬다운 방식(Python wat)이라 한다.

입력값이 리스트로 제공되므로 reverse() 함수를 사용하면 뒤집을 수 있다.

 

만약 입력값이 문자열이라면 이전 문제에서 사용했던 문자열 슬라이싱 [::-1]을 사용할 수 있다.


요약

1. 입력값이 리스트라면 reverse() 함수를 사용해 리스트를 쉽게 뒤집을 수 있다.

 

 

이 글은 파이썬 알고리즘 인터뷰를 공부하면서 정리한 내용입니다.