알고리즘/Problem Solving
[LeetCode] Reverse String
도툐리
2021. 4. 11. 20:23
leetcode.com/problems/reverse-string/
Reverse String - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
(0) 내가 처음에 작성한 코드
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
l = len(s)
for i in range(l//2):
tmp = s[i]
s[i] = s[l-1-i]
s[l-1-i] = tmp
(1) <파이썬 알고리즘 인터뷰> : 투 포인터를 이용한 스왑
-> 전통적인 방식.
-> 내가 한거랑 비슷한거 같은데 훠얼씬 fancy하고 더 가독성 높은 느낌.
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
left, right = 0, len(s) -1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
(2) <파이썬 알고리즘 인터뷰> : 파이썬다운 방식
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s.reverse()
원래는 s[::-1]을 사용해도 정상적으로 처리되어야 하지만,
문제에서는 공간복잡도를 O(1)로 제한했기 때문에 사용 불가능.
대신 s.reverse()를 사용해 한줄로 쉽게 처리 가능.
참고 내용 출처 :
책 <파이썬 알고리즘 인터뷰>