122. Reverse Words in a String

Medium · String

Given a string, reverse the order of the words while maintaining the integrity of each word. A word is defined as a sequence of non-space characters separated by one or more spaces.

After reversing, the result should have a single space between words and no leading or trailing spaces.

Examples

Example 1
Input: "the quick brown fox"
Output: "fox brown quick the"
Explanation: The four words are reversed in order. Each word remains unchanged, only their sequence is reversed.
Example 2
Input: "  hello   world  "
Output: "world hello"
Explanation: Multiple spaces are treated as delimiters. The result has exactly one space between words and no leading/trailing spaces.

Constraints