Given an input string s, reverse the order of the words.

Constraints:

  • A word is defined as a sequence of non-space characters.
  • Words are separated by at least one space.
  • The input string may contain leading or trailing spaces.
  • Multiple spaces between two words should be reduced to a single space in the reversed string.
  • The reversed string should not contain leading or trailing spaces.

Example 1:

Input: "the sky is blue"
Output: "blue is sky the"

Example 2:

Input: "  hello world  "
Output: "world hello"

Example 3:

Input: "a good   example"
Output: "example good a"

Solution

Approach: To efficiently reverse words while handling varying whitespace, a common strategy involves these steps:

  1. Split Words: First, process the input string to extract individual words. Most languages provide a split function that, when used correctly (e.g., without arguments in Python or with a regex for one or more spaces), can automatically handle multiple spaces between words and ignore leading/trailing spaces.
  2. Reverse Word Order: Once you have a list or array of words, reverse the order of these words.
  3. Join Words: Finally, join the reversed list of words back into a single string, using a single space as the separator.

Example Code (Python):

class Solution:
    def reverseWords(self, s: str) -> str:
        # Step 1: Split the string into words.
        # `s.split()` by default splits by any whitespace and discards empty strings,
        # effectively handling multiple spaces and leading/trailing spaces.
        words = s.split()
        
        # Step 2: Reverse the list of words.
        words.reverse()
        
        # Step 3: Join the words with a single space.
        return " ".join(words)