In [3]:
class Solution:
    def reverseWords(self, s: str) -> str:
        words = []
        i = len(s) - 1
        while i >= 0:
            while i >= 0 and s[i] == ' ':
                i -= 1
            if i < 0:
                break
            word_end = i
            while i >= 0 and s[i] != ' ':
                i -= 1
            words.append(s[i + 1 : word_end + 1])
        return " ".join(words)
In [4]:
sol = Solution()
print("Output is :- ",sol.reverseWords("the sky is blue"))
print("Output is :- ",sol.reverseWords("  hello world  "))
print("Output is :- ",sol.reverseWords("a good   example"))
Output is :-  blue is sky the
Output is :-  world hello
Output is :-  example good a