파이썬 알고리즘 인터뷰 문제 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 풀이, 정직한 풀이.
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가 맞다.
일종의 트릭스러운 풀이
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s.reverse()
아! 이 풀이를 보고 든 생각이다. 그래 이렇게 하는게 파이썬스러운 풀이지.