# [Leetcode]344. Reverse String

limelimejiwon·2022년 3월 11일
0

## Python으로 공부하는 코딩테스트

목록 보기
9/67 ## 📄 Description

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"]

## 🔨 My Solution

• use two pointers for exchanging elements

## 💻 My Submission

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

## 🔎 Complexity

Time Complexity: $O(n)$
Space Complexity: $O(1)$

## 💡 Other Approches

### 📌 Pythonic Way(파이썬 다운 방식)

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

### 📌 Using Slicing(슬라이싱)

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

🔴 공간 복잡도가 $O(1)$로 제한되어 있으므로 s=s[::-1]은 통과되지 않는다.

### 💭 s[:]=s[::-1] 랑 s=s[::-1] 가 어떻게 다른데?

s = s[::-1] creates a new local variable s and assigns the reversed list to it, it doesn't modify the list s, whereas s[:] = s[::-1] creates an intermediate reversed list, and assigns it back to s , since we are using slice notation s[:].

References