Reverse words in a given string

Given a string s, reverse the order of the words in the string.

A word is defined as a sequence of non-space characters. The input string may contain leading spaces, trailing spaces, or multiple spaces between words.

The returned string should:

  • Contain the words in reverse order.
  • Have exactly one space between adjacent words.
  • Have no leading or trailing spaces.

Do not reverse the characters within individual words.

Example 1:

Input: s = "coding is fun"

Output: "fun is coding"

Explanation: The words are "coding", "is", and "fun". Reversing their order gives "fun is coding".

Example 2:

Input: s = " learn every day "

Output: "day every learn"

Explanation: Ignoring the extra spaces, the words are "learn", "every", and "day". After reversing their order and placing one space between adjacent words, the result is "day every learn".

Now Your Turn!

Pick the correct output for the given input

Input: s = "hello"

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= s.length <= 104
  • s contains English letters (uppercase and lowercase), digits, and spaces ' '.
  • There is at least one word in s.
0
class Solution {
public:
string reverseWords(string s) {
// Your code goes here
return "";
}
};
Test Case

Input:

S