Medium

Quiz

#151 Reverse Words in a String

APPROACH

Given an input string s, return a new string where the words appear in reverse order.

A word is a maximal run of non-space characters. Words in s may be separated by multiple spaces.

The result must contain only a single space between words, with no leading or trailing spaces.

Example 1:

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

Example 2:

Input: s = " hello world "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: s = "a good example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
1 of 4
1:00

What is the optimal approach for this problem?