Reverse Words in a String

Intuition Split words into a array, build new string using .pop() Approach First split the text by (spaces), then pop the last element, strip whitespaces and concatenete at the end of the new string. Complexity Time complexity: O(n) Space complexity: O(n) Code class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ words = s.strip().split(' ') reversed = '' while len(words) > 0: w = words.pop().strip() if len(w) == 0: continue reversed += w + (' ' if len(words) > 0 else '') return reversed

April 16, 2025 · 1 min