231. Reverse Words in a String

MediumStringString

Given an input string s, reverse the order of the words. A word is a maximal sequence of non-space characters. Collapse multiple spaces and trim leading/trailing spaces so the result has single spaces between words.

Input: A quoted string s.

Output: Quoted string — words in reverse order.

Examples

Example 1
Input: "the sky is blue"
Output: "blue is sky the"
Explanation: Words reversed.
Example 2
Input: "  hello world  "
Output: "world hello"
Explanation: Trimmed and reversed.
Example 3
Input: "a good   example"
Output: "example good a"
Explanation: Spaces collapsed.

Constraints

Asked by

AppleHCLTechMicrosoftBloombergInfosysAmazon
Solve this problem in the editor →