#K32792. Reverse Words While Preserving Spaces
Reverse Words While Preserving Spaces
Reverse Words While Preserving Spaces
You are given a string s
that may contain letters, punctuation, and spaces. Your task is to reverse each word in the string while keeping the spaces in their original positions. A word is defined as a maximal contiguous sequence of characters that are not spaces.
For instance, if s = "Hello World "
, then the output should be "olleH dlroW "
with the exact same spacing.
Note: If the string is empty or consists only of spaces, the output should be identical to the input.
The problem can be mathematically represented as: For each index i in the set of indices corresponding to characters in a word, if the word spans indices \( j \) to \( k \) then the character at position i in the word will be moved to position \( j+k-i \) in the output. Spaces remain fixed.
inputFormat
The input consists of a single string which can include letters, spaces, and punctuation. The string is read from standard input (stdin).
outputFormat
Output a single string to standard output (stdout) that results from reversing every word in the input while preserving the exact positions of the spaces.
## sampleHello World
olleH dlroW