Reverse Words in a String
Medium · two pointers
You are given a string s made of words separated by spaces. A word is a maximal run of characters that are not spaces.
Return a new string with the words in reverse order, joined by exactly one space. The result has no spaces at the start or at the end. The letters inside each word keep their original order.
The input can be untidy: it may start or end with spaces, and it may have several spaces between two words. None of that spacing is kept. The only space character is " ". The string always contains at least one word.
Examples
Example 1
Input: s = " tea and biscuits "
Output: "biscuits and tea"
The three words are tea, and, biscuits. Reversed, they are joined with single spaces, and the extra spaces are dropped.
Example 2
Input: s = "hello"
Output: "hello"
A single word stays as it is.
Example 3
Input: s = "x1 y2 z3"
Output: "z3 y2 x1"
Words can contain digits. Only the order of the words changes, not the characters inside them.
Constraints
- 1 <= len(s) <= 10^4
- s consists of English letters, digits and the space character.
- s contains at least one word.