
[LeetCode] 151. Reverse Words in a String
sum(gas) - sum(cost) < 0이면 불가능)class Solution:
def reverseWords(self, s: str) -> str:
words = s.strip().split()
words_reverse = words[::-1]
output = " ".join(words_reverse)
return output
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(reversed(s.split()))
Both solutions have the same time complexity of , 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 memory and copy time), while reversed() returns an iterator and avoids that overhead.