[LeetCode/Python] 151. Reverse Words in a String

도니·2025년 9월 17일

Interview-Prep

목록 보기
15/29
post-thumbnail

📌 Problem

[LeetCode] 151. Reverse Words in a String

📌 Solution

  • 전체 합(sum(gas) - sum(cost) < 0이면 불가능)

Code 1

class Solution:
    def reverseWords(self, s: str) -> str:
        words = s.strip().split()
        words_reverse = words[::-1]
        output = " ".join(words_reverse)
        return output

Code 2

class Solution:
    def reverseWords(self, s: str) -> str:
        return " ".join(reversed(s.split()))

Both solutions have the same time complexity of O(n)O(n), since the input string must be scanned once.
The difference lies in constant factors: using words[::-1] creates a full copy of the list (extra O(n)O(n) memory and copy time), while reversed() returns an iterator and avoids that overhead.

profile
Where there's a will, there's a way

0개의 댓글