#K85862. Reverse Words in a String

    ID: 36736 Type: Default 1000ms 256MiB

Reverse Words in a String

Reverse Words in a String

You are given a string that may contain leading and trailing whitespace. Your task is to reverse the order of the words in the string. A word is defined as a contiguous sequence of non-space characters. The relative order of spaces at the beginning and end of the string must be preserved exactly, and between every two words there should be exactly one space.

Formally, if the input string is denoted by \(s\), then let \(L\) be the number of leading spaces and \(T\) be the number of trailing spaces. Let \(W\) be the list of words obtained by splitting \(s\) on whitespace. Your task is to produce a string that consists of \(L\) spaces, followed by the words in \(W\) in reverse order separated by a single space, followed by \(T\) spaces.

Examples:

  • Input: " Hello world " → Output: " world Hello "
  • Input: "apple banana cherry" → Output: "cherry banana apple"
  • Input: "OneWord" → Output: "OneWord"
  • Input: " a b c " → Output: " c b a "

Note that if the string consists solely of whitespace, it should be returned unchanged.

inputFormat

The input consists of a single line read from standard input (stdin) containing the string \(s\). The string may contain spaces at the beginning and/or end.

outputFormat

Output the transformed string to standard output (stdout) that has the words in reverse order while preserving the original leading and trailing whitespace and ensuring that there is exactly one space between words.

## sample
   Hello   world 
   world Hello