Cute Running Puppy

algorithm/[python] leetcode

[python] 344. Reverse String

R.silver 2022. 3. 26. 15:43
반응형

https://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

문자열을 뒤집는 문제 
(return을 사용하면 안된다)

풀이 1.

class Solution:
    def reverseString(self, s: List[str]) -> None:
        s.reverse()

 

reverse 함수를 사용

(reverse 함수는 리스트에만 적용가능)

(결과)
Runtime: 379 ms, faster than 12.94% of Python3 online submissions for Reverse String.

풀이2.

class Solution:
    def reverseString(self, s: List[str]) -> None:
        print(s[::-1])

 

문자열 슬라이싱을 사용

(슬라이싱은 리스트와 문자열 모두 사용 가능)

(결과)
출력 결과가 다름 ['o', 'l', 'l', 'e', 'h'] 로 출력됨

(원인)
원래 문자열 슬라이싱은 리스트에도 사용이 가능하다
그런데 이 문제는 공간 복잡도가 O(1)로 제한이 되어 있어 오류가 발생한다.

(해결)
s[:] = s[::-1]

풀이 3. 

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 Pointer 사용 

양 끝단을 포인터로 잡고 중앙으로 움직이며 스왑하는 방식 

(결과)
Runtime: 299 ms, faster than 38.92% of Python3 online submissions for Reverse String.

기타 오류

코드를 올바르게 입력했음에도 파이참에서 계속 아래와 같은 오류가 떴다.

NameError: name 'List' is not defined

 

leetcode에서 list가 아닌 List를 사용해서 발생한 문제로 

코드 상단에 List를 import 해주면 해결된다 

(leetcode에서는 입력하지 않아도 된다)

from typing import List
반응형

'algorithm > [python] leetcode' 카테고리의 다른 글

[python] 15. 3sum  (0) 2022.08.02
[python] 1. Two Sum  (0) 2022.07.24
[python]5. Longest Palindromic Substring  (0) 2022.07.24
[python] 937. Reorder Data in Log Files  (0) 2022.03.26
[python] 125. Valid Palindrome  (0) 2022.03.19