Reverse Words in a String - aloalgo

Reverse Words in a String

Medium

You are given a string s, reverse the order of words.

A "word" is defined as a sequence of non-space characters. Words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note:

  • Your reversed string should not contain leading or trailing spaces.
  • If there are multiple spaces between words, they should be reduced to a single space in the output.

Example 1

Input
"the sky is blue"
Output
"blue is sky the"
Explanation:

The words "the", "sky", "is", "blue" are reversed to their new order.

Example 2

Input
"  hello world  "
Output
"world hello"
Explanation:

Leading and trailing spaces are removed, and the words are reversed.

Example 3

Input
"a good   example"
Output
"example good a"
Explanation:

Multiple spaces between words are reduced to a single space, and the words are reversed.

Loading...
Input
"the sky is blue"
Output
"blue is sky the"

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!