본문 바로가기
Leetcode

[LeetCode] Reverse String 파이썬 (in-place, list.reverse())

by YGSEO 2021. 4. 12.
728x90
class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        
        i, j = 0, len(s) - 1
        while i < j:
            s[i], s[j] = s[j], s[i]
            i += 1
            j -= 1

왼쪽 끝부터, 오른쪽 끝부터

탐색하면서 서로 swap

string의 길이가 짝, 홀 상관없이 i<j 조건에서는 해결됨.


다른 풀이

s가 리스트이기 때문에 list.reverse()를 사용하면 됨.

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

댓글