#K86952. Reverse Words in a String

    ID: 36978 Type: Default 1000ms 256MiB

Reverse Words in a String

Reverse Words in a String

Given a string S containing words separated by spaces (possibly with extra spaces at the beginning, end, or between words), your task is to reverse the order of the words and remove any unnecessary spaces. The output string should have only a single space between words and no leading or trailing spaces.

Note: If the input string is empty or contains only spaces, the output should be an empty string.

Examples:

  • Input: "hello" → Output: "hello"
  • Input: "the sky is blue" → Output: "blue is sky the"
  • Input: " the sky is blue " → Output: "blue is sky the"
  • Input: " " → Output: ""
  • Input: "a b c d e" → Output: "e d c b a"

Your solution should read input from the standard input (stdin) and print the result to the standard output (stdout).

The problem can also be mathematically described as:

$$Output = \text{join}(\text{reverse}(\text{split}(S))) $$

inputFormat

The input consists of a single line containing the string S. The string may include both leading and trailing spaces, as well as multiple spaces between words.

outputFormat

Output a single line that contains the words from S in reversed order with exactly one space between words. If the string is empty or consists only of spaces, output an empty line.

## sample
hello
hello