#C12469. Reverse String with Preserved Spaces
Reverse String with Preserved Spaces
Reverse String with Preserved Spaces
Given a string s
, your task is to reverse the order of the characters in the string while preserving the positions of all spaces. In other words, for each character in the string that is not a space, its position should be replaced by the character from the end of the string (ignoring spaces), without altering the position of any space character.
The problem can be described mathematically as follows: Let \( S = s_1 s_2 \ldots s_n \) be the input string. Define a function \( f(i) \) that is the index of the \( i^{th} \) non-space character in \( S \). Then, for every index \( i \) such that \( s_i \neq ' ' \), it should be replaced by the character corresponding to \( f(k - j + 1) \) where \( j \) is the rank of the character at index \( i \) among non-space characters and \( k \) is the total count of non-space characters.
For example:
- Input:
hello world
→ Output:dlrow olleh
- Input:
a b c d e
→ Output:e d c b a
Note that if the string contains only spaces or is empty, the output should be the same as the input.
inputFormat
The input consists of a single line containing the string s
. The string can include letters, spaces, and other characters. The input is read from standard input (stdin).
outputFormat
Output a single line containing the reversed string with all spaces in their original positions. The output is written to standard output (stdout).
## samplehello world
dlrow olleh