#K6406. Reverse Only Letters in a String
Reverse Only Letters in a String
Reverse Only Letters in a String
You are given a string S consisting of letters and digits. Your task is to reverse the order of the letters in S while keeping the digits in their original positions.
For example, given the input string ab12cd34ef
, the letters when reversed become fe
, dc
, ba
while the digits 1,2,3,4
remain in the same positions, so the output is fe12dc34ba
.
The reversal logic only applies to alphabetic characters (A–Z and a–z). Digits and any other characters, if present, should not be moved.
Note: If there are no letters, the string remains unchanged.
You can mathematically define the process as follows:
Let \( S = s_1 s_2 \dots s_n \) be the input string, and let \( L = [l_1, l_2, \dots, l_k] \) be the sequence of letters (i.e. \( l_i = s_j \) where \( s_j \) is a letter). Let \( L^R = [l_k, l_{k-1}, \dots, l_1] \) be the reversed sequence. Then, for each position \( j \) in \( S \), if \( s_j \) is a letter, replace it with the next element in \( L^R \); otherwise, keep it as is.
inputFormat
The input is provided via standard input (stdin
) as a single line containing the string S. The string may contain alphabetic characters and digits.
outputFormat
Output the transformed string to standard output (stdout
) after reversing only the letters in the string while keeping the digits in their original positions.
ab12cd34ef
fe12dc34ba