본문 바로가기
Programming/LeetCode

[LeetCode] Reverse String

by 데이터현 2022. 2. 28.

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

 

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

문자열을 뒤집는 문제

 

투 포인터 활용

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

 

reverse 함수 활용

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

 

이 문제는 공간 복잡도 때문에 아래 트릭을 이용해서 문제를 풀이할 수 있다.

# 불가능
s = s[::-1]

# 가능
s[:] = s[::-1]

'Programming > LeetCode' 카테고리의 다른 글

[LeetCode] Broken Calculator  (0) 2022.03.23
[LeetCode] Merge Two Sorted Lists  (0) 2022.03.23
[LeetCode] Palindrome Linked List  (0) 2022.03.23
[LeetCode] Valid Palindrome  (0) 2022.02.25
[LeetCode] Two Sum  (0) 2022.02.09

댓글